停止词功能

Die*_*oP. 0 php stop-words

我有这个函数,如果在数组中找到一个坏词,则返回true $stopwords

function stopWords($string, $stopwords) {
    $stopwords = explode(',', $stopwords);
    $pattern = '/\b(' . implode('|', $stopwords) . ')\b/i';
    if(preg_match($pattern, $string) > 0) {
       return true;
    }
    return false;
}
Run Code Online (Sandbox Code Playgroud)

它似乎工作正常.

问题是,当数组$stopwords为空(所以没有指定坏字)时,它总是返回true,就好像空值被识别为坏词并且它总是返回true(我认为这是问题,但可能是另一个) ).

任何人都可以帮我解决这个问题吗?

谢谢

kon*_*ddy 6

我会用in_array():

function stopWords($string, $stopwords) {
   return in_array($string, explode(',',$stopwords));
}
Run Code Online (Sandbox Code Playgroud)

这将节省一些时间而不是正则表达式.


编辑:匹配字符串中的任何单词

function stopWords($string, $stopwords) {
   $wordsArray = explode(' ', $string);
   $stopwordsArray = explode(',',$stopwords);
   return count(array_intersect($wordsArray, $stopwordsArray)) < 1;
}
Run Code Online (Sandbox Code Playgroud)