1

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 !

2

2 Answers 2

3

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.

-1

Maybe this can help you :

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

foreach($array as $value)
{
    $pattern = '/'.$value.'/i';
    $content = preg_replace($pattern, strtolower($value) , $content);
}


echo $content;

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.