phpstringreplacepreg-replaceword-boundary

Replace only whole word matches in a string


I would like to replace just complete words using php

Example : If I have

$text = "Hello hellol hello, Helloz";

and I use

$newtext = str_replace("Hello",'NEW',$text);

The new text should look like

NEW hello1 hello, Helloz

PHP returns

NEW hello1 hello, NEWz

Thanks.


Solution

  • 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);