2011-12-24 54 views

回答

114

在这篇文章中,我会为你提供做你要求什么的三种不同的方法。我实际上建议使用最后一个片段,因为它最容易理解,并且在代码中非常整齐。

如何查看数组中与我的正则表达式匹配的元素?

有一个专门用于此目的的功能,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_reducepreg_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]; 

文档

+2

超凡!谢谢! – 2011-12-24 23:20:26

+1

有人刚刚投了票,我可以问一下背后的原因吗?上述帖子中的内容是正确的,并且是OP要求的内容,请对此进行说明。 – 2011-12-24 23:26:00

+3

不是我;对于一个糟糕的问题来说这是一个很好的答案你应该停止滥用逗号,尽管>。< – 2011-12-24 23:28:16

3

您可以使用array_walkpreg_match功能应用到阵列中的每个元素。

http://us3.php.net/array_walk

+0

这似乎是这个任务过于复杂。 Youd必须使用回调来删除不匹配的项目。 – Galen 2011-12-24 23:11:09

4

使用preg_grep

$array = preg_grep(
    '/(my\n+string\n+)/i', 
    array('file' , 'my string => name', 'this') 
); 
2
$items = array(); 
foreach ($haystacks as $haystack) { 
    if (preg_match($pattern, $haystack, $matches) 
     $items[] = $matches[1]; 
} 
+0

也许使用一个foreach对资源的开支有点复杂... – 2011-12-24 23:18:36

+0

@OlafErlandsen:怎么这样?您需要以某种方式检查每个元素。 “foreach”这样做并不神奇。 – 2011-12-24 23:28:45

+0

preg_grep(Regexp,Array)工作得很好:) – 2011-12-25 00:16:27