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

2022-08-30 11:00:46
$example = array('An example','Another example','Last example');

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

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

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

echo array_search('Last',$example);

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


答案 1

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

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

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

$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


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