Search code examples
phppreg-replacelowercase

How to lowercase a specific word in a string php


Hye Guys !!

I need your help ! Here are 2 elements:

$string = "Legend Of Zelda";
$array = array("to","of","at");

I'd like to check if $string contains one of the $array elements and lowercase it. Tried this, but failed ... i got the felling that the first element of the preg_replace should be a pattern or so ?

echo preg_replace($array, mb_strtolower($array), $string);

Any idea ? Thanks a lot from France !


Solution

  • Use preg_replace_callback:

    $string = "Legend Of Zelda";
    $array = array("to","of","at");
    echo preg_replace_callback('~\b(?:' . implode("|", $array) . ')\b~ui', function ($m) {
        return mb_strtolower($m[0]);
      }, $string);
    

    See PHP demo.

    The regex will look like \b(?:to|of|at)\b here, see its demo online.

    The /i flag will ensure case insensitive search and /u will handle all Unicode chars correctly.