RegEx to Find a Word within a String Using preg_match

When using preg_match to find a word in a string, you’ll find that the default regex used in most examples  (ex: “/needle/i” ) works perfectly fine for finding if a pattern occurs in the string, but if you are looking to find a specific word it can get you unexpected results. For example, if we want to see if a string contains the word “red” and use that regex code we could get positive matches where we did not intend to. Using this on strings like “The man stared at the sun” and “It had to be redone” would both return a value of 1 indicating that they did contain the word “red”.

To ensure that these false positives do not occur, you can use the regex in the following code:

"The barn is red.";
if(preg_match($word$sentence)) {
    echo 'match found';
} else {
    echo 'match not found';

This regex will check to make sure that the character to the left of the word we are searching for will either be the start of the string or a space. It will also check to make sure that the character to right of the word we are searching for is either the end of the string, a space, or a non-alphabetical character. Following normal sentence structure, this allows us to determine whether the provided word is being used as a word and is not accidentally being found as part of some other word in the string.

Example results using our new RegEx:

$sentence = “The barn is red.”; will output ‘match found’
$sentence = “The red car was fast.”; will output ‘match found’
$sentence = “The man stared at the sun.”; will output ‘match not found’
$sentence = “It had to be redone.”; will output ‘match not found’

Code Summary

Regex code for finding a pattern of characters:

Regex code for finding an actual word:

Speak Your Mind