$example = array('An example','Another example','Last example');
如何在上面的数组中松散地搜索单词“Last”?
echo array_search('Last example',$example);
如果指针与值中的所有内容完全匹配,上面的代码只会回显值的键,这是我不想要的。我想要这样的东西:
echo array_search('Last',$example);
如果值包含单词“Last”,我希望值的键能够回显。
要查找符合搜索条件的值,您可以使用 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
包含原始数组中的键值对,其中值包含(不区分大小写)单词 last。