Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?.

like image 269
Iain Simpson Avatar asked Dec 05 '22 09:12

Iain Simpson


2 Answers

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.";
    }
}
like image 172
MrCode Avatar answered Dec 16 '22 00:12

MrCode


Read it somewhere:

if(preg_match('[word1|word2]', $a)) { } 
like image 37
Sankalp Mishra Avatar answered Dec 16 '22 00:12

Sankalp Mishra