搜索包含字符串PHP数组元素 [英] Search for PHP array element containing string

查看:121
本文介绍了搜索包含字符串PHP数组元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我怎样才能为上述阵列中的词最后做一个松散的搜索?

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

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

如果针头匹配的值准确的一切,这是我不想要的东西上面的code将只能随声附和价值的关键。我想是这样的:

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".

推荐答案

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

现在 $匹配数组将包含从原始数组包含Word只元素的最后的(不区分大小写)。

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

现在阵 $匹配包含原始数组,其中值包含键 - 值对(不区分大小写)字的最后

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

这篇关于搜索包含字符串PHP数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆