0

如果在数组中找到坏词之一,我有这个函数返回 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;
}

它似乎工作正常。

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

谁能帮我解决这个问题?

谢谢

4

4 回答 4

6

我会使用in_array()

function stopWords($string, $stopwords) {
   return in_array($string, explode(',',$stopwords));
}

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


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

function stopWords($string, $stopwords) {
   $wordsArray = explode(' ', $string);
   $stopwordsArray = explode(',',$stopwords);
   return count(array_intersect($wordsArray, $stopwordsArray)) < 1;
}
于 2012-02-07T11:53:28.367 回答
0

将 $stopwords 作为数组给出

function stopWords($string, $stopwords) {
    //Fail in safe mode, if $stopwords is no array
    if (!is_array($stopwords)) return true;
    //Empty $stopwords means all is OK
    if (sizeof($stopwords)<1) return false;
    ....
于 2012-02-07T11:55:03.537 回答
0

如果数组$stopwords为空,则explode(',', $stopwords)计算为空字符串并$pattern等于/\b( )\b/i$stopwords这就是如果为空,您的函数返回 true 的原因。

修复它的最简单方法是添加一条if语句来检查数组是否为空。

于 2012-02-07T12:04:53.900 回答
-1

你可以这样写一个条件:

if (!empty ($stopwords)) { your code} else {echo ("no bad words");}

然后要求用户或应用程序输入一些不好的词。

于 2012-02-07T11:54:00.463 回答