问题描述
$example = array('An example','Another example','Last example');
如何在上述数组中对单词Last"进行松散搜索?
How can I do a loose search for the word "Last" in the above array?
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);
如果值包含单词Last",我希望值的键回显.
And I want the value's key to echo if the value contains the word "Last".
推荐答案
要查找符合您搜索条件的值,您可以使用 array_filter
函数:
To find values that match your search criteria, you can use array_filter
function:
$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(不区分大小写)的元素.
Now $matches
array will contain only elements from your original array that contain word last (case-insensitive).
如果你需要找到符合条件的值的键,那么你需要遍历数组:
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;
}
}
现在数组 $matches
包含来自原始数组的键值对,其中值包含(不区分大小写)单词 last.
Now array $matches
contains key-value pairs from the original array where values contain (case- insensitive) word last.
这篇关于搜索包含字符串的 PHP 数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!