How to Check If a String Contains a Specific Word in PHP?

Finding a word in a string means that the string "are", for example, will only be matched when the word "are" itself is in the string. This means that words containing "are" (such as "area", "fare", "dares", etc.) will return false. This is an important distinction to make between checking for a word within a string and checking for a substring within a string. In this article, we will focus on finding a word within a string.

Using preg_match() With a Word Boundary

You can use regular expressions with a word boundary (\b) to match only when the word exists in the string. The function returns 1 if match is found, 0 if no match is found or false if there was an error. For example:

preg_match('/\bare\b/', 'how are you?'); // 1

preg_match('/\bare\b/', 'area, fares, dares should not match'); // 0

In this approach, we assume the words are separated by a space, so in cases where the word might be separated by something else (for example, "how_are_you?"), it won't match unless you update your regular expression to look for such cases.

Matching Words With Punctuation Marks:

You can simply update your regular expression to include punctuation marks (such as comma, fullstop, question mark, exclaimation mark, etc.). For example:

preg_match('/\byou[?|.|,|!]?\b/', 'How are you?'); // 1

Alternatively, you could also do the following to remove all unicode punctuation characters:

preg_match('/\byou\pP?\b/', 'How are you?'); // 1

\pP is a PCRE character set that denotes all unicode punctuation characters. Since this is a bit out of the scope of this article, perhaps you can read up more on it if you want.

Case-Insensitive Matching:

To do case-insensitive matching, we need to use the i flag with our regular expression like so:

preg_match('/\bare\b/i', 'How Are You?'); // 1

Exploding Words Into an Array and Using in_array()

We could split the string into an array based on a delimeter (such as space) and then use in_array() function to look for a specific word:

$string = 'How are you?';
$chunks = explode(' ', $string);

if (in_array('are', $chunks)) {
    echo 'Found the word "are"';
}

// output: 'Found the word "are"'
$string = 'Area, fares, dares should not match';
$chunks = explode(' ', $string);

if (! in_array('are', $chunks)) {
    echo 'Not found';
}

// output: 'Not found'

Matching Words With Punctuation Marks:

You can remove all punctuation marks (using \pP) from the string before you look for matches, for example:

$string = 'How are you?';
$subject = preg_replace('/\pP/', '', $string);
$chunks = explode(' ', $subject);

if (in_array('you', $chunks)) {
    echo 'Found the word "you"';
}

// output: 'Found the word "you"'

If you do not wish to make use of regular expressions, then you could use str_replace() and specify an array of punctuations you wish to strip out, for example:

$string = 'How are you?';
$subject = str_replace(['?', '!', ',', '.'], '', $string);
$chunks = explode(' ', $subject);

if (in_array('you', $chunks)) {
    echo 'Found the word "you"';
}

// output: 'Found the word "you"'

Case-Insensitive Matching:

To do case-insensitive matching with in_array() we could convert the case of each word into a common case (such as lowercase) and then do the matching:

$string = 'How Are You?';
$chunks = explode(' ', $string);
$lcChunks = array_map('strtolower', $chunks);

if (in_array('are', $lcChunks)) {
    echo 'Found the word "are"';
}

// output: 'Found the word "are"'

However, since in_array() does a linear search though the array until it finds the value (i.e. it has a time complexity of O(n)), this has an obvious shortcoming of being slow when used multiple times if the array is too big. One way around this could be to flip the array values to keys and use isset() instead for a faster lookup as it has a time complexity of O(1):

$string = 'How Are You?';
$chunks = explode(' ', $string);
$lcChunks = array_change_key_case(array_flip($chunks), CASE_LOWER);

if (isset($lcChunks['are'])) {
    echo 'Found the word "are"';
}

// output: 'Found the word "are"'

This post was published (and was last revised ) by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.