2013-12-20 61 views
0

我有一组单词和一组停用词。我想要从停用词数组中删除那些单词中的单词,但代码会返回所有单词:使用array_filter过滤数组

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

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

为什么?

+2

[Working](http://codepad.viper-7.com/mxhGZE)对我很好。 – Rikesh

+0

是的,它很酷。 –

+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'是字符串还是数组?

+0

虽然这是我的错,代码也没问题,但我接受此解决方案以提供示例 – erdomester

0

//应当是数组
$ wordArray =阵列( '他', '是', '去', '到', '床');

//应该返回布尔
功能禁用词($ X)
{
回报的preg_match(“/ ^(|!一个|汽车|红色|的|它在|或| |的|是|为|至)$ /”,$ X);
}

//器阵列
$滤波器= array_filter($ wordArray, “停止词”);

//输出
echo“< pre>”;
print_r($ filter);

//结果
阵列

[0] =>他
[2] =>去
[4] =>床

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);