在这篇文章中,我将为您提供三种不同的方法来满足您的要求。 我实际上建议使用最后一个代码段,因为它最容易理解并且代码简洁。
如何查看数组中与我的正则表达式匹配的元素?
有专门用于此目的的功能
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];


