2010-12-15 21 views
2

我想使用preg_match来为括号内的子模式返回每个匹配的数组。preg_match中相同类型的多个匹配

我有这样的代码:

$input = '[one][two][three]'; 

    if (preg_match('/(\[[a-z0-9]+\])+/i', $input, $matches)) 
    { 
     print_r($matches); 
    } 

此打印:

Array ([0] => [one][two][three], [1] => [three]) 

...只返回满弦和最后一场比赛。我想要它回来:

Array ([0] => [one][two][three], [1] => [one], [2] => [two], [3] => [three]) 

这可以用preg_match完成吗?

回答

2

使用preg_match_all()+下降。

$input = '[one][two][three]'; 

if (preg_match_all('/(\[[a-z0-9]+\])/i', $input, $matches)) { 
    print_r($matches); 
} 

给出:

Array 
(
    [0] => Array 
     (
      [0] => [one] 
      [1] => [two] 
      [2] => [three] 
     ), 

    [1] => Array 
     (
      [0] => [one] 
      [1] => [two] 
      [2] => [three] 
     ) 
) 
1
$input = '[one][two][three]'; 

if (preg_match_all('/(\[[a-z0-9]+\])+/iU', $input, $matches)) 
{ 
    print_r($matches); 
}