Search code examples
phpregexreplaceword-boundary

Case-insensitively replace whole words only


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 occurrence.

So, I want to find each occurrence of the word me and replace it with xxx so that Me meets smeg becomes xxx meets smeg. In other words, Me meets smeg should not become xxx xxxets sxxg.

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


Solution

  • Try the following regex:

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

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