Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
252 views
in Technique[技术] by (71.8m points)

html - make first letter caps in php but ucfirst(strtolower('string')) does not work

I've been trying to make the first letter of a string in the capital but I can't get it to work.

I have tried the following code:

 <?php

$str = $_POST['Papier'];

$f = highlightKeywords('papierwaren', $str);
$s = strtolower($f);
$r = ucfirst($s);

function highlightKeywords($text, $keyword)
{

    $pos = strpos($text, $keyword);

    $wordsAry = explode(" ", $keyword);

    $wordsCount = count($wordsAry);

    for ($i = 0; $i < $wordsCount; $i++) {
        if ($pos === false) {
            $highlighted_text = "<span style='font-weight:700;color:#151313;'>" . strtolower($wordsAry[$i]) . "</span>";
        } else {
            $highlighted_text = "<span style='font-weight:700;color:#151313;'>" . $wordsAry[$i] . "</span>";
        }
        $text = str_ireplace($wordsAry[$i], $highlighted_text, $text);
    }

    return $text;
}

still, I am not getting it to work and I tried if whitespace occurs with the following

$r=ucfirst(trim($s));

still not succeeded. This 'papierwaren' text i'm getting it form db so pls someone help me to resolve this.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As Kaddath said, You are adding HTML to your string (<span ...). When you use ucfirst it changes the first char to uppercase but the first char is now <, the uppercase for < is <.

Try this code:

<?php

$str = 'papier';

$f = highlightKeywords('papierwaren', $str);

echo $f;

function highlightKeywords($text, $keyword)
{

    $pos = strpos($text, $keyword);

    $wordsAry = explode(" ", $keyword);

    $wordsCount = count($wordsAry);

    for ($i = 0; $i < $wordsCount; $i++) {
        if ($pos === false) {
            if ($i === 0) {
                $highlighted_text = "<span style='font-weight:700;color:#151313;'>" . ucfirst(strtolower($wordsAry[$i])) . "</span>";
            } else {
                $highlighted_text = "<span style='font-weight:700;color:#151313;'>" . strtolower($wordsAry[$i]) . "</span>";
            }
        } else {
            if ($i === 0) {
                $highlighted_text = "<span style='font-weight:700;color:#151313;'>" . ucfirst($wordsAry[$i]) . "</span>";
            } else {
                $highlighted_text = "<span style='font-weight:700;color:#151313;'>" . $wordsAry[$i] . "</span>";
            }
        }
        $text = str_ireplace($wordsAry[$i], $highlighted_text, $text);
    }

    return $text;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...