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 !

Hymed Ghenai
  • 181
  • 14
  • 1
    Moreover, [mb_strtolower()](https://www.php.net/manual/en/function.mb-strtolower.php) requires a `string` as parameter, not an array. [How do I get PHP errors to display?](https://stackoverflow.com/questions/1053424/how-do-i-get-php-errors-to-display?rq=1) might help with errors – brombeer Jul 29 '20 at 09:19
  • 2
    `foreach($array as $element) $string = str_ireplace($element, strtolower($element), $string);`. You simply can adopt to mb. – Markus Zeller Jul 29 '20 at 09:24

2 Answers2

1

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.

Wiktor Stribiżew
  • 484,719
  • 26
  • 302
  • 397
-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;
Mohammed Yassine CHABLI
  • 2,692
  • 2
  • 13
  • 36