Check if a string contain multiple specific words

后端 未结 6 1228
独厮守ぢ
独厮守ぢ 2020-12-04 16:46

How to check, if a string contain multiple specific words?

I can check single words using following code:

$data = "text text text text text text t         


        
6条回答
  •  难免孤独
    2020-12-04 17:30

    strpos does search the exact string you pass as second parameter. If you want to check for multiple words you have to resort to different tools

    regular expressions

    if(preg_match("/\b(bad|naughty)\b/", $data)){
        echo "Found";
    }
    

    (preg_match return 1 if there is a match in the string, 0 otherwise).

    multiple str_pos calls

    if (strpos($data, 'bad')!==false or strpos($data, 'naughty')!== false) {
        echo "Found";
    }
    

    explode

    if (count(array_intersect(explode(' ', $data),array('bad','naugthy')))) {
        echo "Found";
    }
    

    The preferred solution, to me, should be the first. It is clear, maybe not so efficient due to the regex use but it does not report false positives and, for example, it will not trigger the echo if the string contains the word badmington

    The regular expression can become a burden to create if it a lot of words (nothing you cannot solve with a line of php though $regex = '/\b('.join('|', $badWords).')\b/';

    The second one is straight forward but can't differentiate bad from badmington.

    The third split the string in words if they are separated by a space, a tab char will ruins your results.

提交回复
热议问题