Finding and Replacing Whole Word Matches in a String
When working with strings, it's common to need to replace specific words or phrases. However, simply using a string replacement function like str_replace() can lead to unexpected results, as it replaces all occurrences of the pattern regardless of its position within a word.
To address this, regular expressions can be employed to match only whole word instances of a pattern. The key to this is the word boundary metacharacter, denoted by "b".
Using Regular Expressions
To replace only whole word matches, use the following regular expression pattern:
/\bHello\b/
Here's a breakdown of the pattern:
Example Implementation
Consider the following PHP code:
<?php $text = "Hello hellol hello, Helloz"; $newtext = preg_replace('/\bHello\b/', 'NEW', $text); echo $newtext; ?>
Explanation:
Output:
NEW hello1 hello, Helloz
Unicode Considerations
If your text contains Unicode characters, you may need to add the "u" modifier to the regular expression to handle non-latin characters correctly:
$newtext = preg_replace('/\bHello\b/u', 'NEW', $text);
The above is the detailed content of How Can I Replace Whole Words in a String Using Regular Expressions?. For more information, please follow other related articles on the PHP Chinese website!