有两个数组:
$strings = array('Apple', 'Banana', 'Orange');
$substrings = array('pp', 'range');
我想得到一个包含所有字符串的数组,匹配子字符串:
Array
(
[0] => Apple
[2] => Orange
)
或使用新索引:
Array
(
[0] => Apple
[1] => Orange
)
想到一个简单的解决方案:组合array_filter
and strpos
;
$strings = array('Apple', 'Banana', 'Orange');
$substrings = array('pp', 'range');
$result = array_filter($strings, function($item) use($substrings) {
foreach($substrings as $substring)
if(strpos($item, $substring) !== FALSE) return TRUE;
return FALSE;
});
要重置索引,您可以使用该array_values
功能。
$strings = array('Apple', 'Banana', 'Orange');
$substrings = array('pp', 'range');
$newarray = array();
foreach ($strings as $string) {
foreach ($substrings as $substring) {
if (strstr($string, $substring)) {
array_push($newarray, $string);
}
}
}
在$newarray
你有结果
您可以为此使用array_filter:
$strings = array('Apple', 'Banana', 'Orange');
$substrings = array('pp', 'range');
$result = array_filter($strings, function($string) use ($substrings){
foreach($substrings as $substring)
if(strstr($string, $substring) !== false)
return true;
return false;
});
// $result is the result you want.
尝试数组搜索。以本页底部的第二个注释http://php.net/manual/en/function.array-search.php为例。
$arr=array();
foreach($substrings as $item)
{
$result=array_keys($strings,$item);
if ($result)
{
$arr=array_merge($arr,$result);
}
}