Search code examples
phphtmlstringlaraveluppercase

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.


Solution

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