开发者

Multiple matches of the same type in preg_match

开发者 https://www.devze.com 2023-01-31 06:43 出处:网络
I want to use preg_match to return an array of every match for parenthesized subpattern. I have this code:

I want to use preg_match to return an array of every match for parenthesized subpattern.

I have this code:

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

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

This prints:

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

... only returning the full string and the last match. I would like it to return:

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

Can th开发者_如何学JAVAis be done with preg_match?


Use preg_match_all() with the + dropped.

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

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

Gives:

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

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


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

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

精彩评论

暂无评论...
验证码 换一张
取 消