PHP string replace match whole word

You want to use regular expressions. The \b matches a word boundary.

$text = preg_replace('/\bHello\b/', 'NEW', $text);

If $text contains UTF-8 text, you’ll have to add the Unicode modifier “u”, so that non-latin characters are not misinterpreted as word boundaries:

$text = preg_replace('/\bHello\b/u', 'NEW', $text);

Leave a Comment