如何使用preg_match在数组中搜索?如何用preg_match在数组中搜索?
例子:
<?php
if(preg_match('/(my\n+string\n+)/i' , array('file' , 'my string => name', 'this') , $match))
{
//Excelent!!
$items[] = $match[1];
} else {
//Ups! not found!
}
?>
如何使用preg_match在数组中搜索?如何用preg_match在数组中搜索?
例子:
<?php
if(preg_match('/(my\n+string\n+)/i' , array('file' , 'my string => name', 'this') , $match))
{
//Excelent!!
$items[] = $match[1];
} else {
//Ups! not found!
}
?>
在这篇文章中,我会为你提供做你要求什么的三种不同的方法。我实际上建议使用最后一个片段,因为它最容易理解,并且在代码中非常整齐。
有一个专门用于此目的的功能,preg_grep
。它将采用正则表达式作为第一个参数,并将数组作为第二个参数。
见下面的例子:
$haystack = array (
'say hello',
'hello stackoverflow',
'hello world',
'foo bar bas'
);
$matches = preg_grep ('/^hello (\w+)/i', $haystack);
print_r ($matches);
输出
Array
(
[1] => hello stackoverflow
[2] => hello world
)
array_reduce
与preg_match
可以用干净的方式解决这个问题;请参阅下面的代码片段。
$haystack = array (
'say hello',
'hello stackoverflow',
'hello world',
'foo bar bas'
);
function _matcher ($m, $str) {
if (preg_match ('/^hello (\w+)/i', $str, $matches))
$m[] = $matches[1];
return $m;
}
// N O T E :
// ------------------------------------------------------------------------------
// you could specify '_matcher' as an anonymous function directly to
// array_reduce though that kind of decreases readability and is therefore
// not recommended, but it is possible.
$matches = array_reduce ($haystack, '_matcher', array());
print_r ($matches);
输出
Array
(
[0] => stackoverflow
[1] => world
)
文档
array_reduce
似乎很乏味,是不是有另一种方式?是的,这一个实际上是更清洁,虽然它不涉及使用任何预先存在的array_*
或preg_*
函数。
如果您打算多次使用此方法,请将其封装在一个函数中。
$matches = array();
foreach ($haystack as $str)
if (preg_match ('/^hello (\w+)/i', $str, $m))
$matches[] = $m[1];
文档
您可以使用array_walk
您preg_match
功能应用到阵列中的每个元素。
这似乎是这个任务过于复杂。 Youd必须使用回调来删除不匹配的项目。 – Galen 2011-12-24 23:11:09
$array = preg_grep(
'/(my\n+string\n+)/i',
array('file' , 'my string => name', 'this')
);
$items = array();
foreach ($haystacks as $haystack) {
if (preg_match($pattern, $haystack, $matches)
$items[] = $matches[1];
}
也许使用一个foreach对资源的开支有点复杂... – 2011-12-24 23:18:36
@OlafErlandsen:怎么这样?您需要以某种方式检查每个元素。 “foreach”这样做并不神奇。 – 2011-12-24 23:28:45
preg_grep(Regexp,Array)工作得很好:) – 2011-12-25 00:16:27
超凡!谢谢! – 2011-12-24 23:20:26
有人刚刚投了票,我可以问一下背后的原因吗?上述帖子中的内容是正确的,并且是OP要求的内容,请对此进行说明。 – 2011-12-24 23:26:00
不是我;对于一个糟糕的问题来说这是一个很好的答案你应该停止滥用逗号,尽管>。< – 2011-12-24 23:28:16