tags:

views:

142

answers:

5

I know this is really easy, and I've done it a million times myself; but it's late in the day and I have a brain meltdown.

I'm trying to match and replace whole words rather than every occurance.

So, I want to replace each occurance of the word 'me' and replace it with 'xxx'

Ie. 'Me meets smeg' becomes 'xxx meets smeg'

What I DO NOT want is:

'Me meets smeg' becomes 'xxx xxxets sxxg'

I know it's preg_match but I just can't remember the pattern matching for whole words.

Please help

Oliver.

+1  A: 

\b matches a word boundary, so something like /\bMe\b/ (or /\bme\b/i for case insensitivity) should give you the regex you desire!

Paul Dixon
+1  A: 

You use the \b word boundary.

$str = preg_replace('/\bMe\b/', 'xx', $str);

For case insensitivity, use the i modifier:

$str = preg_replace('/\bme\b/i', 'xx', $str);
Blixt
+2  A: 

Word boundary characters

$output = preg_replace( "/\\bme\\b/", 'xxx', $input );
Peter Bailey
+4  A: 
$replaced = preg_replace('/\bme\b/i','xxx',$phrase);
Question Mark
A: 

Try the following regex:

$replaced = preg_replace('/\bme\b/i', 'xxx', $subject);

\b is the word boundry as defined in the PCRE Reference.

Andrew Moore