使用array_filter过滤数组

时间:2013-12-20 09:21:49

标签: php

我有一系列单词和一系列停用词。我想从停用词数组中的单词数组中删除这些单词,但代码返回所有单词:

function stopwords($x){
      return !preg_match("/^(.|a|car|red|the|this|at|in|or|of|is|for|to)$/",$x);
    };

$filteredArray = array_filter($wordArray, "stopwords");

为什么?

3 个答案:

答案 0 :(得分:1)

$wordArray = ["hello","red","world","is"];

function stopwords($x){
      return !preg_match("/^(.|a|car|red|the|this|at|in|or|of|is|for|to)$/",$x);
    };

$filteredArray = array_filter($wordArray, "stopwords");
var_dump($filteredArray);

# results out:
array(2) {
   [0] =>   string(5) "hello"   
   [2] =>   string(5) "world"
}

你认为它会回归什么?

您的输入'$ wordArray'是字符串还是数组?

答案 1 :(得分:0)

  

//应该是阵列
   $ wordArray = array('he','is','going','to','bed');

     

//应该返回布尔值   功能停用词($ x)
  {
       return!preg_match(“/ ^(。| a | car | red | the | this | at | in |或| of | is | for | to)$ /”,$ x);
  }   
  //过滤器阵列
  $ filter = array_filter($ wordArray,“stopwords”);
  
  //输出
  echo“< pre>”;
  的print_r($过滤器);
   

     

//结果
  阵列
  (
          [0] =>他           [2] =>去           [4] =>床   )

答案 2 :(得分:0)

试试这个..

    $words = array('apple','boll','cat','dog','elephant','got');
        $stopwords = array('cat','apple');

       foreach($words as $k=>$v)
        {
        if(in_array($v,$stopwords)){
            unset($words[$k]);  
        }

      }
print_r($words);