在 php 数组中搜索部分字符串匹配 [英] search a php array for partial string match
本文介绍了在 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的preg_grep函数.PHP >= 4.0.5 支持.
You can use preg_grep 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屋!
查看全文