2012-01-10 57 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); 
相關問題