phpregexstringreplaceword-boundary

Replace "whole word" when "word" starts with colon (\b is not working as intended)


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 should the regex be adjusted?

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


Solution

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

    $str = preg_replace('/:Name\b/i', '"Test"', $str);