Efficient way to test string for certain words

前端 未结 6 1755
一整个雨季
一整个雨季 2020-12-17 08:03

I have a bunch of banned words and want to check if string A contains any of these words.

For example:

$banned_words = \"dog cat horse bird mouse mon         


        
6条回答
  •  情话喂你
    2020-12-17 08:53

    You can use str_ireplace, to check for bad words or phrases. This can be done in a single line of PHP code without the need for nested loops or regex as follows:

    $banstring = ($string != str_ireplace($badwords,"XX",$string))? true: false;
    

    This approach has the added benefit of being case insensitive. To see this in action, you could implement the check as follows:

    $string = "The quick brown fox jumped over the lazy dog";
    $badwords = array('dog','cat','horse','bird','mouse','monkey');
    $banstring = ($string != str_ireplace($badwords,"XX",$string))? true: false;
    if ($banstring) {
        echo 'Bad words found';
    } else {
        echo 'No bad words in the string';
    }
    

    If the list of bad words is a string rather than an array (as in the question), then the string can be turned into an array as follows:

    $banned_words = "dog cat horse bird mouse monkey"; //etc
    $badwords = explode(" ", $banned_words);
    

提交回复
热议问题