我需要一个简单的文字过滤器,如果它在字符串中检测到过滤后的字,就会终止该脚本。
说我的话如下
$showstopper = array(badword1, badword2, badword3, badword4);
$yourmouth = "im gonna badword3 you up";
if(something($yourmouth, $showstopper)){
//stop the show
}
答案 0 :(得分:6)
你可以将坏词数组内爆成正则表达式,看看它是否与haystack匹配。或者您可以简单地遍历数组,并单独检查每个单词。
来自评论:
$re = "/(" . implode("|", $showstopper) . ")/"; // '/(badword1|badword2)/'
if (preg_match($re, $yourmouth) > 0) { die("foulmouth"); }
答案 1 :(得分:1)
in_array()是你的朋友
$yourmouth_array = explode(' ',$yourmouth);
foreach($yourmouth_array as $key=>$w){
if (in_array($w,$showstopper){
// stop the show, like, replace that element with '***'
$yourmouth_array[$key]= '***';
}
}
$yourmouth = implode(' ',$yourmouth_array);
答案 2 :(得分:1)
您可能希望将此与foreach
和preg_match
方法进行对比。
$showstopper = array('badword1', 'badword2', 'badword3', 'badword4');
$yourmouth = "im gonna badword3 you up";
$check = str_replace($showstopper, '****', $yourmouth, $count);
if($count > 0) {
//stop the show
}
答案 3 :(得分:1)
快速解决方案涉及检查密钥,因为这不需要遍历数组。但是,这需要修改你的坏词列表。
$showstopper = array('badword1' => 1, 'badword2' => 1, 'badword3' => 1, 'badword4' => 1);
$yourmouth = "im gonna badword3 you up";
// split words on space
$words = explode(' ', $yourmouth);
foreach($words as $word) {
// filter extraneous characters out of the word
$word = preg_replace('/[^A-Za-z0-9]*/', '', $word);
// check for bad word match
if (isset($showstopper[$word])) {
die('game over');
}
}
preg_replace 可确保用户不会通过输入 bad_word3 等内容来滥用您的过滤器。它还确保阵列密钥检查不会轰炸。
答案 4 :(得分:0)
不确定为什么你需要这样做但是有一种方法可以检查并获得使用过的坏词
$showstopper = array(badword1, badword2, badword3, badword4);
$yourmouth = "im gonna badword3 you up badword1";
function badWordCheck( $var ) {
global $yourmouth;
if (strpos($yourmouth, $var)) {
return true;
}
}
print_r(array_filter($showstopper, 'badWordCheck'));
array_filter()返回一个错误单词数组,所以如果它的count()为0,则表示不好,