2011-05-25 64 views
1

我試圖找出一個字符串匹配IE我的任何不好的話在我的陣列相匹配:檢查是否任何數組中的字符串的字符串

$badWords = Array('bad', 'words', 'go', 'here'); 
$strToCheck = "checking this string if any of the bad words appear"; 

if (strpos($strToCheck, $badWords)) { 
    // bad word found 
} 

問題是strpos只能檢查對於一個字符串而不是一個數組,是否有一種方法可以在沒有循環遍歷字符串數組的情況下執行此操作?

+0

看看這個功能http://2008.gr0w.com/articles /代碼/ php_bad_words_filter / – 2011-05-25 22:10:30

回答

0

in_array 閱讀問題錯誤。

簡單的實現是調用strpos()爲每個BADWORDS的:

<?php 
$ok = TRUE; 
foreach($badwords AS $word) 
{ 
    if(strpos($strToCheck, $word)) 
    { 
     $ok = FALSE; 
     break; 
    } 
} 
?> 
3

不完全是,因爲所有的解決方案必然要遍歷您的陣列,即使是「幕後」。您可以從$ badWords中創建正則表達式,但運行時複雜性可能不會受到影響。總之,這裏是我的正則表達式的建議:

$badWordsEscaped = array_map('preg_quote', $badWords); 
$regex = '/'.implode('|', $badWordsEscaped).'/'; 
if(preg_match($regex, $strToCheck)) { 
    //bad word found 
} 

請注意,我逃出來防止正則表達式,注射的話,如果他們包含任何特殊的正則表達式字符,如/.

2

array_intersect()讓你列表匹配單詞:

if (count(array_intersect(preg_split('/\s+/', $strToCheck), $badWords))) { 
    // ... 
} 
0

試試這個..

$badWords = array('hello','bad', 'words', 'go', 'here'); 
$strToCheck = 'i am string to check and see if i can find any bad words here'; 
//Convert String to an array 
$strToCheck = explode(' ',$strToCheck); 

foreach($badWords as $bad) { 
    if(in_array($bad, $strToCheck)) { 
     echo $bad.'<br/>'; 
    } 
} 

上面的代碼將返回所有匹配的不良詞,你可以進一步擴展它來實現你自己的邏輯,如替換不好的詞等

相關問題