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

Use*_*upt 38 php arrays

$example = array('An example','Another example','Last example');
Run Code Online (Sandbox Code Playgroud)

如何在上面的数组中松散搜索"Last"一词?

echo array_search('Last example',$example);
Run Code Online (Sandbox Code Playgroud)

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

echo array_search('Last',$example);
Run Code Online (Sandbox Code Playgroud)

如果值包含单词"Last",我希望值的键回显.

Ale*_*s G 54

要查找符合搜索条件的值,您可以使用以下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); });
Run Code Online (Sandbox Code Playgroud)

现在$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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

  • 这在技术上没有任何问题,但我一生都无法理解为什么在此处使用正则表达式不会`strpos()` 工作得一样好并且速度更快? (2认同)

Way*_*tty 19

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

  • @MarcioSimao 这只会返回第一个匹配元素的键,而不是所有匹配项的键数组。 (2认同)

xda*_*azz 8

$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;
}));
Run Code Online (Sandbox Code Playgroud)

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