3

可以说我有一系列不好的词:

$badwords = array("one", "two", "three");

和随机字符串:

$string = "some variable text";

如何创建此循环:

if (one or more items from the $badwords array is found in $string)
echo "sorry bad word found";
else
echo "string contains no bad words";

示例:
如果$string = "one fine day" or "one fine day two of us did something",用户应该看到“抱歉找到错误的单词”消息。
如果$string = "fine day",用户应该看到字符串不包含坏词消息。

据我所知,你不能preg_match从数组中。有什么建议吗?

4

4 回答 4

7

这个怎么样:

$badWords = array('one', 'two', 'three');
$stringToCheck = 'some stringy thing';
// $stringToCheck = 'one stringy thing';

$noBadWordsFound = true;
foreach ($badWords as $badWord) {
  if (preg_match("/\b$badWord\b/", $stringToCheck)) {
    $noBadWordsFound = false;
    break;
  }
}
if ($noBadWordsFound) { ... } else { ... }
于 2012-04-27T22:15:24.823 回答
5

为什么要在preg_match()这里使用?
那这个呢:

foreach($badwords as $badword)
{
  if (strpos($string, $badword) !== false)
    echo "sorry bad word found";
  else
    echo "string contains no bad words";
}

如果preg_match()出于某些原因需要,您可以动态生成正则表达式模式。像这样的东西:

$pattern = '/(' . implode('|', $badwords) . ')/'; // $pattern = /(one|two|three)/
$result = preg_match($pattern, $string);

高温高压

于 2012-04-27T22:18:43.710 回答
2

如果你想通过将字符串分解成单词来检查每个单词,你可以使用这个:

$badwordsfound = count(array_filter(
    explode(" ",$string),
    function ($element) use ($badwords) {
        if(in_array($element,$badwords)) 
            return true; 
        }
    })) > 0;

if($badwordsfound){
   echo "Bad words found";
}else{
   echo "String clean";
}

现在,我想到了更好的事情,如何替换数组中的所有坏词并检查字符串是否保持不变?

$badwords_replace = array_fill(0,count($badwords),"");
$string_clean = str_replace($badwords,$badwords_replace,$string);
if($string_clean == $string) {
    echo "no bad words found";
}else{
    echo "bad words found";
}
于 2012-04-27T22:16:02.187 回答
1

这是我使用的坏词过滤器,效果很好:

private static $bad_name = array("word1", "word2", "word3");

// This will check for exact words only. so "ass" will be found and flagged 
// but not "classic"

$badFound = preg_match("/\b(" . implode(self::$bad_name,"|") . ")\b/i", $name_in);

然后我有另一个变量与选择字符串匹配:

// This will match "ass" as well as "classic" and flag it

private static $forbidden_name = array("word1", "word2", "word3");

$forbiddenFound = preg_match("/(" . implode(self::$forbidden_name,"|") . ")/i", $name_in);

然后我运行if它:

if ($badFound) {
   return FALSE;
} elseif ($forbiddenFound) {
   return FALSE;
} else {
   return TRUE;
}

希望这可以帮助。问你是否需要我澄清任何事情。

于 2012-04-27T22:18:09.607 回答