Check if a string contains specific words in PHP

This code snippet shows you how to check if a string contains a specific word in PHP, or if a string contains a match from an array of word options.

Check if a string contains a specific word

The function we'll need for this snippet is strpos, which can be used in the following format:

mixed strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )

String pos will find the position of the first occurence of a character or series of characters within in a string, represented as searching for a $needle in a $haystack. If you want to ignore some characters within your string / haystack, then you can use the offset parameter to set how many characters to ignore from the start of the string (cannot be negative).

While strpos will return the numerical position of the needle found, which isn't useful to us in this scenario, we know it will return FALSE If there was no match, therefore we can use the following snippet as a check for word a match within a string:

if (strpos($haystack, $needle) !== false) {
    echo 'Match found';
}

So the following code would return Match Found.

if (strpos('brown','the quick brown fox') !== false) {
    echo 'Match found';
}

As strpos can return '0' as a positive result, we use !== to compare the values to avoid false positives.

Check if a string contains a word from an array

So what if we had an array of words, and we wanted to check if any of them match? We can adapt the above code into a function like so:

function match($needles, $haystack)
{
    foreach($needles as $needle){
        if (strpos($haystack, $needle) !== false) {
            return true;
        }
    }
    return false;
}

You can then call this function as follows:

$needles = array('dog','cat');
$haystack = 'I have a cat';
if(match($needles, $haystack)){
   echo "Matching pet.";
}

Check if a string contains all words in an array

Lastly, what if we want to match all words in an array?

function match_all($needles, $haystack)
{
    if(empty($needles)){
        return false;
    }

    foreach($needles as $needle) {
        if (strpos($haystack, $needle) == false) {
            return false;
        }
    }
    return true;
}

In this example we add a check to make sure that the needles array isn't empty, which would return a false positive.

You can then call this function as follows:

$needles = array('dog','cat');
$haystack = 'I have a cat and a dog';
if(match_all($needles, $haystack)){
   echo "Matching pets.";
}
Sign Up

NEXT: How to turn on error reporting in PHP

How to switch on PHP error reporting directly in the code, and a quick overview of how error reporting works and the options available.

comments powered by Disqus
Sign Up

Popular Tags

Need a web developer?

If you'd like to work with code synthesis on your next project get in touch via the contact page.