2015-06-19 46 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'; 
}