0

有没有办法在下面提到的坏词过滤器代码中实现 if else ,这样当用户输入任何坏词时,它会给出错误“您的输入包含不允许的词”而不是替换坏词

FUNCTION BadWordFilter(&$text, $replace){

$file_array = file('/path/to/badword.txt');


$bads = array();
foreach ($file_array as $word_combo) {
$bads[] = explode(',', $word_combo);
}



IF($replace==1) {                                        //we are replacing
  $remember = $text;

  FOR($i=0;$i<sizeof($bads);$i++) {               //go through each bad word
       $text = EREGI_REPLACE($bads[$i][0],$bads[$i][1],$text); //replace it
  }

  IF($remember!=$text) RETURN 1;                     //if there are any changes, return 1

} ELSE {                                                  //we are just checking

  FOR($i=0;$i<sizeof($bads);$i++) {               //go through each bad word
       IF(EREGI($bads[$i][0],$text)) RETURN 1; //if we find any, return 1
  }     
 }

}

$any = BadWordFilter($qtitle,1); 
$any = BadWordFilter($qtitle,0); 
4

1 回答 1

0

如果我理解正确,您只需要一种方法来判断函数的返回值是否表明“坏词”已被替换或找到。鉴于您目前拥有的内容,您已经知道是否要替换它们,您只需要在return 0;方法的末尾添加一个,这将表明没有进行替换或没有找到坏词。

我已经以应该处理此问题的方式重写了您的示例。在重写中,我还分别更改了您对eregi_replace()and eregi()withpreg_replace()和的用法preg_match()。前两种方法已弃用,不应使用。此外,我还没有测试以下内容,它仅作为概念验证:

function BadWordFilter(&$text, $replaceWords = false) {
    $file_array = file('/path/to/badword.txt');
    $bads = array();
    foreach ($file_array as $word_combo) $bads[] = explode(',', $word_combo);

    if ($replaceWords == true) {
        $original = $text;
        foreach ($bads as $bad) {
            // replace any bad word instance
            $text = str_replace($bad[0], $bad[1], $text);
        }
        // check if bad words have been replaced
        return ($text == $original) ? false : true;
    } else {
        foreach ($bads as $bad) {
            if (strpos($text, $bad[0]) !== false) {
                // found a bad word
                return true;
            }
        }
        // no bad words found
        return false;
    }
}

$error = '';
// replace words:
if (BadWordFilter($qtitle, true)) {
    $error = 'Your input contained bad words and they have been replaced.';
}
// don't replace words:
if (BadWordFilter($qtitle, false)) {
    $error = 'Your input contains words that are not allowed.';
}

更新:在“坏词”文件中看到示例输入文本后,不需要正则表达式。我已经分别用和替换了preg_replace()和的原始替换。preg_match()str_replace()strpos()

于 2012-07-25T16:13:55.027 回答