2010-04-21 97 views
0

有比strpos()循环更好的方法吗?是否有一个本地php函数来查看一个值的数组是否在另一个数组中?

不是我正在寻找部分匹配而不是in_array()类型的方法。

例如针和干草堆和期望的回报:

$needles[0] = 'naan bread'; 
$needles[1] = 'cheesestrings'; 
$needles[2] = 'risotto'; 
$needles[3] = 'cake'; 

$haystack[0] = 'bread'; 
$haystack[1] = 'wine'; 
$haystack[2] = 'soup'; 
$haystack[3] = 'cheese'; 

//desired output - but what's the best method of getting this array? 
$matches[0] = 'bread'; 
$matches[1] = 'cheese'; 

即:

magic_function($大海捞针,%$针%)!

+0

[array_intersect](http://www.php.net/manual/en/function.array-intersect.php) – hsz 2010-04-21 18:21:31

+0

不,不会比'bread'针对'烤饼bread'。 OP似乎在寻找通配符匹配功能。 – 2010-04-21 18:22:19

+0

这将适用于非完全匹配吗? – Haroldo 2010-04-21 18:23:06

回答

2

我想你混淆了你的问题$haystack$needle,因为烤饼面包不在草堆,也不是cheesestring。您期望的产量表明您正在寻找干酪 in 干酪串。为此,下面将工作:

function in_array_multi($haystack, $needles) 
{ 
    $matches = array(); 
    $haystack = implode('|', $haystack); 
    foreach($needles as $needle) { 
     if(strpos($haystack, $needle) !== FALSE) { 
      $matches[] = $needle; 
     } 
    } 
    return $matches; 
} 

了给定的草垛和针头这个执行快两倍,正则表达式的解决方案。虽然可能会改变不同数量的参数。

3
foreach($haystack as $pattern) { 
    if (preg_grep('/'.$pattern.'/', $needles)) { 
     $matches[] = $pattern; 
    } 
} 
+1

短而甜。 – 2010-04-21 18:24:41

+0

function magic_function($ haystack,$ needles){ // code above above here :) } – hsz 2010-04-21 18:39:42

+0

返回一个包含四个元素的数组:面包,奶酪,面包,奶酪 – Gordon 2010-04-21 18:40:55

1

我想你必须自己推出。用户提供的评论array_intersect()提供了一些替代实现(如this one)。您只需将==替换为strstr()即可。

1
$data[0] = 'naan bread'; 
$data[1] = 'cheesestrings'; 
$data[2] = 'risotto'; 
$data[3] = 'cake'; 

$search[0] = 'bread'; 
$search[1] = 'wine'; 
$search[2] = 'soup'; 
$search[3] = 'cheese'; 

preg_match_all(
    '~' . implode('|', $search) . '~', 
    implode("\x00", $data), 
    $matches 
); 

print_r($matches[0]); 

// [0] => bread 
// [1] => cheese 

如果你告诉我们更多关于真正问题你会得到更好的答案。

相关问题