2015-06-19 107 views
1

如何使用stripos過濾掉本身存在的不需要的單詞。 如何扭轉下面的代碼,在文法中搜索'won'將不會返回true,因爲'wonderful'本身就是另一個詞。在邏輯過濾中使用PHP stripos()

$grammar = 'it is a wonderful day'; 
$bad_word = 'won'; 

$res = stripos($grammar, $bad_word,0); 

if($res === true){ 
     echo 'bad word present'; 
}else{ 
     echo 'no bad word'; 
} 

//result 'bad word present' 
+1

您是否嘗試過的preg_match()?或者在變量的開始/結尾添加一個空格?既然你正在尋找「won」這個詞,那麼當它包含在一個句子中時,它應該有一個左邊或右邊的空格。 –

+0

謝謝,我認爲preg_match()會工作,如果(preg_match(「/ \ bwon \ b /我」,「這是一個美好的一天」)){ 回聲「找到壞詞」。 } else { echo「bad word not found。」; } //找不到錯誤的單詞 –

回答

1
$grammar = 'it is a wonderful day'; 
$bad_word = 'won'; 

     /* \b \b indicates a word boundary, so only the distinct won not wonderful is searched */ 

if(preg_match("/\bwon\b/i","it is a wonderful day")){ 
    echo "bad word was found";} 
else { 
    echo "bad word not found"; 
    } 

//result is : bad word not found 
1

使用preg_match

$grammar = 'it is a wonderful day'; 
$bad_word = 'won'; 
$pattern = "/ +" . $bad_word . " +/i"; 

// works with one ore more spaces around the bad word, /i means it's not case sensitive 

$res = preg_match($pattern, $grammar); 
// returns 1 if the pattern has been found 

if($res == 1){ 
    echo 'bad word present'; 
} 
else{ 
    echo 'no bad word'; 
}