简体   繁体   中英

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.

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;
}

In laravel this should help

use Illuminate\Support\Str;

$testString = 'this is a sentence.';

$uppercased = Str::ucfirst($testString);

Do not forget to import Illuminate\Support\Str to controller.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM