使用PHP在数组中查找字符串

时间:2012-12-19 08:53:57

标签: php arrays string explode implode

我有2个数组,我希望使用PHP在数组1中找到一个值。

我意识到我必须使用PHP explode函数,但我担心这会影响我的技能。

我的函数会比较两个数组的值,如果它在$needle中找到任何$haystack值,它会在$found内返回它们。它可能会找到多个,所以也许$found也应该是一个数组?

$needle = "Swimming,Landscaping,Gardening,Bricklaying,3D Modelling";
$haystack = "Football,Rugby,Landscaping,3D Modelling";
$found = magicFunction($needle,$haystick); 
// $found['0'] = "Landscaping";
// $found['1'] = "3D Modelling";

这有意义吗?

非常感谢您提出的任何指示。

5 个答案:

答案 0 :(得分:7)

PHP提供了方便的功能array_intersect来实现这一目标。

$needle = "Swimming,Landscaping,Gardening,Bricklaying,3D Modelling";
$haystack = "Football,Rugby,Landscaping,3D Modelling";

$needle = explode(",", $needle);
$haystack = explode(",", $haystack);

$intersection = array_intersect($haystack, $needle);
print_r($intersection);
//Array ( [2] => Landscaping [3] => 3D Modelling )

答案 1 :(得分:3)

你可以这样做:

$found = Array ();
$needle = "Swimming,Landscaping,Gardening,Bricklaying,3D Modelling";
$haystack = "Football,Rugby,Landscaping,3D Modelling";
$search = explode(',',$haystack);
foreach ( explode(',',$needle as $k => $v )
{
  if ( in_array ( $v, $search ) )
    $found[] = $v;
}

或者正如大卫所说,你可以使用array_intersect

$found = array_intersect ( explode( ',', $haystack ), explode( ',', $needle ) );

答案 2 :(得分:1)

你可以从针和大海捞针生成数组,然后找到两个数组的交叉点:

<?php

$needle = "Swimming,Landscaping,Gardening,Bricklaying,3D Modelling";
$haystack = "Football,Rugby,Landscaping,3D Modelling";

$needle = explode(',', $needle);
$haystack = explode(',', $haystack);


$found = array_intersect($needle, $haystack);

print_r($found);
?>

http://tr1.php.net/array_intersect

答案 3 :(得分:1)

您正在寻找的功能内置于PHP:array_intersect

$a = explode(',', "Swimming,Landscaping,Gardening,Bricklaying,3D Modelling");
$b = explode(',', "Football,Rugby,Landscaping,3D Modelling");
$found = array_intersect($a, $b); 
print_r($found);

输出: Array ( [1] => Landscaping [4] => 3D Modelling )

答案 4 :(得分:0)

最简单的方法可能是使用strpos来爆炸针并查找事件。

$needles = explode(',', $needle);
foreach ($needles as $n)
{
      if (strpos($n, $haystack)) {  }
}
如果您不需要字符串的位置,

Jan Hančič解决方案可能更合适更快。