2012-01-10 58 views
0

我有一堆被禁止的单词,并希望检查字符串A是否包含任何这些单词。有效的方法来测试字符串的某些单词

例如:

$banned_words = "dog cat horse bird mouse monkey blah blah2 blah3 "; //etc 
$string_A = "The quick brown fox jumped over the lazy dog"; 

我怎样才能有效地检查,看看是否有任何字符串中的单词,任何在禁用词语列表中的单词匹配?

+1

这已经完成了数千次。搜索谷歌或stackoverflow'PHP坏字'或什么,你会发现一打不同的解决方案。例如这:http://stackoverflow.com/questions/5615146/check-a-string-for-bad-words欢呼 – Chris 2012-01-10 10:08:52

+0

谢谢,在编程方面,'坏字'这个短语对我来说是陌生的。如果我知道的话,我会用Google搜索。干杯 – dukevin 2012-01-10 10:11:58

+0

没问题,那就是我想的。欢呼 – Chris 2012-01-10 10:12:46

回答

3
if (preg_match('~\b(' . str_replace(' ', '|', $banned_words) . ')\b~', $string_A)) { 
    // there is banned word in a string 
} 
1

如果$banned_w是一个数组不会更好?

然后你可以explode()你想检查被禁止的字符串,然后对每个爆炸片使用in_array()来检查它是否是禁止的字。

编辑: 如果有人修改坏字,您可以使用:similar_text进行比较。

+0

扫描一个字符串N次(对于每个单词)效率不高,我想 – zerkms 2012-01-10 10:11:48

+0

我想到了最初的想法,但我没有认为搜索每个字符串的大小数组[在这里插入大数字]将是有效的。 – dukevin 2012-01-10 10:13:10

0

这将是一个容易许多创造的屏蔽词数组,然后使用str_replace与阵列,像这样:

$banned_words = array('dog', 'cat', 'horse', 'bird', 'mouse', 'monkey', 'blah', 'blah2', 'blah3'); 
$string_A = "The quick brown fox jumped over the lazy dog"; 
echo str_replace($banned_words, "***", $string_A); 

将输出:The quick brown fox jumped over the lazy ***

0

我只是开发了一个功能可以过滤掉不好的话:

function hate_bad($str) 
{ 
    $bad=array("shit","ass"); 
    $piece=explode(" ",$str); 
    for($i=0;$i < sizeof($bad); $i++) 
    { 
     for($j=0;$j<sizeof($piece);$j++) 
     { 
      if($bad[$i]==$piece[$j]) 
      { 
       $piece[$j]=" ***** "; 
      } 
     } 
    } 

    return $piece; 
} 

,并调用它像这样:

$str=$_REQUEST['bad'];// here bad is the name of tex field<br/><br/> 
$good=hate_bad($str); <br/> 

if(isset($_REQUEST['filter']))// 'filter' name of button 
{ 
    for($i=0;$i<sizeof($good);$i++) 
    {<br/> 
     echo $good[$i]; 
    } 
} 
0

您可以使用str_ireplace来检查错误的单词或短语。这可以在PHP代码一行完成无需嵌套循环或正则表达式如下:

$banstring = ($string != str_ireplace($badwords,"XX",$string))? true: false; 

这种方法的是不区分大小写的好处。要看到这个动作,你可以实现在检查的过程如下:

$string = "The quick brown fox jumped over the lazy dog"; 
$badwords = array('dog','cat','horse','bird','mouse','monkey'); 
$banstring = ($string != str_ireplace($badwords,"XX",$string))? true: false; 
if ($banstring) { 
    echo 'Bad words found'; 
} else { 
    echo 'No bad words in the string'; 
} 

如果不好的话列出的是一个字符串,而不是一个数组(如题),那么字符串可以变成一个数组如下:

$banned_words = "dog cat horse bird mouse monkey"; //etc 
$badwords = explode(" ", $banned_words); 
相关问题