Check if string contains one of several words

2019-05-09 10:44发布

问题:

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

回答1:

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.";
    }
}


回答2:

Read it somewhere:

if(preg_match('[word1|word2]', $a)) { } 


回答3:

If you have a fixed number of words, which is not too big you can easily make it like this:

$a = 'How are you ?';

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


回答4:

if (strpos($ro1['title'], $search)!==false or strpos($ro1['description'], $search)!== false or strpos($udetails['user_username'], $search)!== false)
{
//excute ur code
}