4

我想要一种从 $keywords 中删除 $badwords 元素的简单方法。

我有什么(例如)

$keywords = array('sebastian','nous','helene','lol'); //it could be anything in fact
$badwords = array('nous', 'lol', 'ene', 'seba'); //array full of stop words that I won't write here
$filtered_keywords = array_filter(preg_replace($badwords,'',$keywords), 'strlen');
print_r($filtered_keywords);

我所期望的

Array ( [0] => samaha [1] => helene ) 

我得到了什么

 Sweet nothing :)

我尝试使用str_ireplace但它变坏了,因为它在我的数组中的字符串中替换。

4

5 回答 5

3
$keywords = array('sebastian','nous','helene','lol');

$badwords = array('nous', 'lol', 'ene', 'seba'); 

$filtered_keywords=array_diff($keywords,$badwords);
于 2012-12-26T07:39:25.667 回答
2

采用array_diff

var_dump(array_diff($keywords, $badwords));
array(2) {
  [0]=>
  string(9) "sebastian"
  [2]=>
  string(6) "helene"
}
于 2012-12-26T07:39:02.093 回答
1

最有可能的数组名称不正确

$filtered_keywords = array_filter(preg_replace($excluded_words,'',$keywords), 'strlen');

它不是$excluded_words,而是$badwords

于 2012-12-26T07:36:52.280 回答
1

您在之后缺少一个分号

$keywords = array('sebastian','nous','helene','lol')

你可以使用array_diff

$filtered_keywords = array_diff($keywords, $badwords);
于 2012-12-26T07:38:52.453 回答
0

您错过了/$badwords 中的斜线。你错过了;第一行末尾的分号。试试这个代码:

<?php

$keywords = array('sebastian','nous','helene','lol'); //it could be anything in fact
$badwords = array('/nous/', '/lol/', '/ene/', '/seba/'); //array full of stop words that I won't write here

$filtered_keywords = array_filter(preg_replace($badwords,'',$keywords), 'strlen');

echo print_r($filtered_keywords);

?>
于 2012-12-26T07:41:30.460 回答