Phong Hoang Phong Hoang - 1 year ago 80
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 Source

Just add word boundary \b in your regex:

$name = preg_replace("/\b$v\b/i", $k, $name);
//              here __^^  ^^
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download