Iain Simpson Iain Simpson - 1 month ago 9
PHP Question

Check if string contains one of several words

I am trying to make a word filter in php, and I have come across a previous Stackoverlow post that mentions the following to check to see if a string contains certain words. What I want to do is adapt this so that it checks for various different words in one go, without having to repeat the code over and over.

$a = 'How are you ?';

if (strpos($a,'are') !== false) {
echo 'true';
}


Will it work if I mod the code to the following ?......

$a = 'How are you ?';

if (strpos($a,'are' OR $a,'you' OR $a,'How') !== false) {
echo 'true';
}


What is the correct way of adding more than one word to check for ?.

Answer

To extend your current code you could use an array of target words to search for, and use a loop:

$a = 'How are you ?';

$targets = array('How', 'are');

foreach($targets as $t)
{
    if (strpos($a,$t) !== false) {
        echo 'one of the targets was found';
        break;
    }
}

Keep in mind that the use of strpos() in this way means that partial word matches can be found. For example if the target was ample in the string here is an example then a match will be found even though by definition the word ample isn't present.

For a whole word match, there is an example in the preg_match() documentation that can be expanded by adding a loop for multiple targets:

foreach($targets as $t)
{
    if (preg_match("/\b" . $t . "\b/i", $a)) {
        echo "A match was found.";
    } else {
        echo "A match was not found.";
    }
}
Comments