搜索php数组以查找部分字符串匹配 [英] search a php array for partial string match

查看:390
本文介绍了搜索php数组以查找部分字符串匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组,我想搜索字符串'green'.因此,在这种情况下,它应该返回$arr[2]

I have an array and I'd like to search for the string 'green'. So in this case it should return the $arr[2]

$arr = array(0 => 'blue', 1 => 'red', 2 => 'green string', 3 => 'red');

是否有像in_array()这样的预定义函数可以完成工作而不是遍历它并比较每个值?

is there any predefined function like in_array() that does the job rather than looping through it and compare each values?

推荐答案

您可以使用php的array_search函数.在PHP> = 4.0.5中受支持.

You can use array_search function of php. It's supported in PHP >= 4.0.5.

$array = array(0 => 'blue', 1 => 'red', 2 => 'green string', 3 => 'red');
$m_array = preg_grep('/^green\s.*/', $array);

$m_array包含数组的匹配元素.

$m_array contains matched elements of array.

这篇关于搜索php数组以查找部分字符串匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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