views:

272

answers:

3

Hello, I would like to make a whole word replace 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.

+1  A: 
preg_replace('/hello\b/i','NEW',$_text)
stillstanding
what does the /i mean ?
nevergone
make the comparison case-insensitive, so it matches Hello, hello, hElLo, hellO, etc.
stillstanding
-1 @stillstanding: If you look at the examples you will see the comparison should be case sensitive.
Majid
Nothing in the example says it should be
stillstanding
Well it does, it says the output should be: `NEW hello1 hello, NEWz`, as you see, `NEW` only replaces instances of `Hello`, but leaves `hello` unchanged as the case does not match.
Majid
@Majid, the `hello,` is unchanged because there's a comma right after it!
stillstanding
And commas just happen to be word boundaries, so the replacement does happen. Obviously you didn't test your own code =\ There's no point posting first if: 1- it's wrong, 2- it's not correctly explained.
Josh Davis
+5  A: 

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);
Lethargy
A: 

Hi,

FYI: I tried this preg_replace. Its not working as expected in UTF-8 characters.

Abu Sithik
You have to use the Unicode modifier for that. I have updated the accepted answer.
Josh Davis
Awesome! Thanks Davis.
Abu Sithik