Phong Hoang Phong Hoang - 5 months ago 13
PHP Question

Preg_replace with array element

I have array like below:

function func($name){
$arr = [
'dog' => 'boo|pet|chinsu|lu',
'man' => 'david|peter|john|smith',
'woman' => 'marry|daisy|anna|tailor'
foreach($arr as $k=>$v) {
$name = preg_replace("/($v)/i",$k,$name);
return $name;

echo func('john'); //return 'man' => OK
echo func('peter'); //return 'doger' => Not OK

It should return 'man' instead of 'doger', but 'pet' also exist in 'peter'.

How can I fix this but still using preg_replace?


Just add word boundary \b in your regex:

$name = preg_replace("/\b$v\b/i", $k, $name);
//              here __^^  ^^