search包含string的PHP数组元素

$example = array('An example','Another example','Last example'); 

如何在上面的数组中search单词“Last”?

 echo array_search('Last example',$example); 

上面的代码只会回应价值的关键,如果针正好匹配的值的一切,这是我不想要的。 我想要这样的东西:

 echo array_search('Last',$example); 

如果值包含单词“Last”,我希望该值的键回显。

要find符合search条件的值,可以使用array_filter函数:

 $example = array('An example','Another example','Last example'); $searchword = 'last'; $matches = array_filter($example, function($var) use ($searchword) { return preg_match("/\b$searchword\b/i", $var); }); 

现在, $matches数组将只包含原始数组中包含单词last (不区分大小写)的元素。

如果您需要查找与条件匹配的值的键,则需要遍历数组:

 $example = array('An example','Another example','One Example','Last example'); $searchword = 'last'; $matches = array(); foreach($example as $k=>$v) { if(preg_match("/\b$searchword\b/i", $v)) { $matches[$k] = $v; } } 

现在,数组$matches包含原始数组中的键值对,其中值最后包含(不区分大小写)的单词。

 function customSearch($keyword, $arrayToSearch){ foreach($arrayToSearch as $key => $arrayItem){ if( stristr( $arrayItem, $keyword ) ){ return $key; } } } 
 $input= array('An example','Another example','Last example'); $needle = 'Last'; $ret = array_keys(array_filter($input, function($var) use ($needle){ return strpos($var, $needle) !== false; })); 

这将给你所有的价值包含针的钥匙。

它find了第一个匹配的元素的键:

 echo key(preg_grep('/\b$searchword\b/i', $example)); 

如果你需要所有的键使用foreach:

 foreach (preg_grep('/\b$searchword\b/i', $example) as $key => $value) { echo $key; } 

我也在寻找解决OP的问题,我偶然发现了这个问题,通过谷歌。 然而,这些答案都没有为我所做,所以我想出了一些不同的东西,运作良好。

 $arr = array("YD-100 BLACK", "YD-100 GREEN", "YD-100 RED", "YJ-100 BLACK"); //split model number from color $model = explode(" ",$arr[0]) //find all values that match the model number $match_values = array_filter($arr, function($val,$key) use (&$model) { return stristr($val, $model[0]);}, ARRAY_FILTER_USE_BOTH); //returns //[0] => YD-100 BLACK //[1] => YD-100 GREEN //[2] => YD-100 RED 

这只适用于PHP 5.6.0及以上版本。