字符串中的preg_match数组项?

时间:2012-04-27 21:49:15

标签: php algorithm preg-match string-parsing

让我们说我有一系列坏话:

$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 个答案:

答案 0 :(得分:6)

这个怎么样:

$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 { ... }

答案 1 :(得分: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);

HTH

答案 2 :(得分: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";
}

答案 3 :(得分: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;
}

希望这会有所帮助。问你是否需要我澄清任何事情。