搜索包含字符串的 PHP 数组元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12315536/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 03:19:38  来源:igfitidea点击:

Search for PHP array element containing string

phparrays

提问by UserIsCorrupt

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

How can I do a loose search for the word "Last" in the above array?

如何在上述数组中对单词“Last”进行松散搜索?

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

The code above will only echo the value's key if the needle matches everything in the value exactly, which is what I don't want. I want something like this:

如果指针与值中的所有内容完全匹配,上面的代码只会回显值的键,这是我不想要的。我想要这样的东西:

echo array_search('Last',$example);

And I want the value's key to echo if the value contains the word "Last".

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

回答by Aleks G

To find values that match your search criteria, you can use array_filterfunction:

要查找与您的搜索条件匹配的值,您可以使用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); });

Now $matchesarray will contain only elements from your original array that contain word last(case-insensitive).

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

If you need to find keys of the values that match the criteria, then you need to loop over the array:

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

$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;
    }
}

Now array $matchescontains key-value pairs from the original array where values contain (case- insensitive) word last.

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

回答by Wayne Whitty

function customSearch($keyword, $arrayToSearch){
    foreach($arrayToSearch as $key => $arrayItem){
        if( stristr( $arrayItem, $keyword ) ){
            return $key;
        }
    }
}

回答by xdazz

$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;
}));

This will give you all the keys whose value contain the needle.

这将为您提供其值包含针的所有键。

回答by aDaemon

It finds an element's key with first match:

它找到第一个匹配项的元素的键:

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

And if you need all keys use foreach:

如果您需要所有键,请使用 foreach:

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

回答by Josan Iracheta

I was also looking for a solution to OP's problem and I stumbled upon this question via Google. However, none of these answers did it for me so I came up with something a little different that works well.

我也在寻找 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

This will only work with PHP 5.6.0 and above.

这仅适用于 PHP 5.6.0 及更高版本。

回答by Dario

I do not like regex because as far as I know they are always slower than a normal string function. So my solution is:

我不喜欢正则表达式,因为据我所知,它们总是比普通的字符串函数慢。所以我的解决方案是:

function substr_in_array($needle, array $haystack) { foreach($haystack as $value) { if(strpos($value, $needle) !== FALSE) return TRUE; } return FALSE; }

function substr_in_array($needle, array $haystack) { foreach($haystack as $value) { if(strpos($value, $needle) !== FALSE) return TRUE; } return FALSE; }

回答by Dario

The answer that Aleks G has given is not accurate enough.

Aleks G 给出的答案不够准确。

$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;
    }
}

The line

线

if(preg_match("/\b$searchword\b/i", $v)) {

should be replaced by these ones

应该被这些替换

$match_result = preg_match("/\b$searchword\b/i", $v);
if( $match_result!== false && $match_result === 1 ) {

Or more simply

或者更简单

if( preg_match("/\b$searchword\b/i", $v) === 1 ) {

In agreement with http://php.net/manual/en/function.preg-match.php

同意http://php.net/manual/en/function.preg-match.php

preg_match() returns 1 if the pattern matches given subject, 0 if it does not, or FALSE if an error occurred.

如果模式匹配给定主题,则 preg_match() 返回 1,如果不匹配则返回 0,如果发生错误则返回 FALSE。