Hymed Ghenai
Hymed Ghenai

Reputation: 199

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 !

Upvotes: 1

Views: 510

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626758

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.

Upvotes: 3

Yassine CHABLI
Yassine CHABLI

Reputation: 3724

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;

Upvotes: -1

Related Questions