【问题标题】:Stop Words function停用词功能
【发布时间】:2012-02-28 20:23:00
【问题描述】:

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

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

它似乎工作正常。

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

谁能帮我解决这个问题?

谢谢

【问题讨论】:

    标签: php stop-words


    【解决方案1】:

    我会使用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;
    }
    

    【讨论】:

    • 恐怕这会失败:in_array() 将返回 true,仅当 完整的 $string 是停用词,但如果 $string 中的单词则不会 是停用词
    • @EugenRieck:我添加了一个用于检查整个字符串中的单个事件的解决方案
    • @konsolenfreddy ... 这让你得到了我的 +1!
    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      将 $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;
          ....
      

      【讨论】:

        【解决方案4】:

        你可以这样写一个条件:

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

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-02-14
          • 1970-01-01
          • 2021-03-11
          • 1970-01-01
          • 2023-03-10
          • 1970-01-01
          相关资源
          最近更新 更多