Phong Hoang Phong Hoang - 3 months ago 6
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?

Answer

Just add word boundary \b in your regex:

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