Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

str_replace: Match whole word only

Since str_replace() matches ":Name" two times in ":Name :Name_en" I want to match the results for the whole word only. I wanted to switch to preg_replace() because of this answer.

$str = ":Name :Name_en";
echo $str . chr(10);
$str = preg_replace('/\b' . ':Name' . '\b/i', '"Test"', $str);
echo $str;

But this doesn't work because of the colon. No replacement takes place. How would the RegExp will look like?

\b is the word boundary. But I think a colon doesn't belong to such a word boundary.

like image 356
testing Avatar asked Mar 13 '12 10:03

testing


1 Answers

You don't need the word boundary on the start of your string:

$str = preg_replace('/:Name\b/i', '"Test"', $str);
like image 182
Evert Avatar answered Oct 20 '22 00:10

Evert