2012-04-27 41 views
1

可以说我有不好的话数组:preg_match字符串中的数组项?

$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从数组。任何建议?

+0

$ string是百达一个随机字符串,它的搜索查询更具体的。所以如果访问者输入包含不好的单词的查询,他应该看不到任何结果,否则..那么你明白了吗? :) – DadaB 2012-04-27 22:00:35

+0

和**是的,你可以'preg_match' **一个数组,你只需要先崩溃它。检查我给出的答案。 – 2012-04-28 00:29:12

回答

5

如何:

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

就像一个魅力。非常感谢! – DadaB 2012-04-28 13:36:50

+0

我用你的代码阿拉伯文字符串,它工作正常。第二天,我试图运行代码没有任何修改,但给了我错误的结果。问题出在preg_match函数中。请帮忙吗? – Fshamri 2015-09-20 20:54:36

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"; 
} 
+1

我建议在'\ b'之类的东西上进行分割,否则当逗号或其他分隔符跟随时,不好的单词会运行。) – raina77ow 2012-04-27 22:17:26

+0

嘿看看我接受之前添加的第二个解决方案:D – 2012-04-27 22:21:28

+0

使用此解决方案时要小心“clbuttic错误”。 – 2012-04-27 22:39:42

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; 
} 

希望这有助于。询问你是否需要我澄清任何事情。

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