preg_match中相同类型的多个匹配项

时间:2010-12-15 18:15:32

标签: php regex 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 个答案:

答案 0 :(得分: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 :(得分:1)

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

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