Check if string contains word in array

后端 未结 12 1483
旧巷少年郎
旧巷少年郎 2020-12-01 09:12

This is for a chat page. I have a $string = \"This dude is a mothertrucker\". I have an array of badwords: $bads = array(\'truck\', \'shot\', etc)

12条回答
  •  爱一瞬间的悲伤
    2020-12-01 10:16

    There is a very short php script that you can use to identify bad words in a string which uses str_ireplace as follows:

    $string = "This dude is a mean mothertrucker";
    $badwords = array('truck', 'shot', 'ass');
    $banstring = ($string != str_ireplace($badwords,"XX",$string))? true: false;
    if ($banstring) {
       echo 'Bad words found';
    } else {
        echo 'No bad words in the string';
    }
    

    The single line:

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

    does all the work.

提交回复
热议问题