多个array_filter和strpos [英] Multiple array_filter and strpos
本文介绍了多个array_filter和strpos的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想返回不包含字符列表的数组。
I want to return array that does not contains a list of characters.
下面的代码对于一个关键字('bc'
)。
Below code works fine for one keyword ('bc'
).
$array = array("abc", "def", "ghi");
$filterArray = array_filter($array, function ($var) {return(strpos($var, 'bc') === false);});
print_r($filterArray);
但是,当我尝试使用<$ c $过滤掉多个关键字时,以下代码不起作用c> $ excludeKeyword_arr 和 foreach
。
However, below code does not work when I try to filter out multiple keywords by using $excludeKeyword_arr
and foreach
.
$array = array("abc", "def", "ghi");
$excludeKeyword_arr = ("ab", "de");
foreach($excludeKeyword_arr as $exclude){
$filterArray = array_filter($array, function ($var) {return(strpos($var, $exclude) === false);});
}
print_r($filterArray);
应为返回数组,而不是布尔类型。
It should be return array instead of boolean type.
推荐答案
您可以使用preg_grep进行相反的操作,并匹配具有 bc
或的对象de
然后array_diff。
You can use preg_grep which will do the opposite and match the ones that has bc
or de
then array_diff.
$array = array("abc", "def", "ghi");
$excludeKeyword_arr = array("bc", "de");
$exclude_values = preg_grep("/". implode("|", $excludeKeyword_arr) . "/", $array);
$filterArray = array_diff($array, $values_with_bc);
print_r($filterArray); // [ 2 => "ghi"]
这篇关于多个array_filter和strpos的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文