2012-02-07 183 views
0

我有这个功能,如果的脏话一个数组$stopwords停止词功能

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

它似乎好工作中发现,返回true。

问题是,当数组$stopwords为空(因此没有指定错误词)时,它总是返回true,就像空值被识别为坏词一样,它总是返回true(我认为问题是这个但也许是另一个)。

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

感谢

回答

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; 
} 
+0

不错的一个!很干净! – Mike 2012-02-07 11:54:44

+0

我担心,这会失败:只有**完整的$ string **是一个停用词时,'in_array()'才会返回true,但如果** $ string **中的某个词是停用词,则不会返回 – 2012-02-07 11:57:38

+0

@EugenRieck:我已经添加了一个解决方案,用于检查整个字符串中的单个事件 – konsolenfreddy 2012-02-07 12:09:16

-1

你可以把一个条件是这样的:

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

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

0

给$禁用词作为数组

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; 
    .... 
0

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

解决它的最简单方法是添加if语句来检查数组是否为空。