Get repeated matches with preg_match_all()

会有一股神秘感。 提交于 2019-11-27 02:14:29
Benjamin

According to Kobi (see comments above):

PHP has no support for captures of the same group

Therefore this question has no solution.

Using lookbehind is a way to do the job:

$list = '1,2,3,4';
preg_match_all('|(?<=\d),\d+|', $list, $matches);
print_r($matches);

All the ,\d+ are in group 0.

output:

Array
(
    [0] => Array
        (
            [0] => ,2
            [1] => ,3
            [2] => ,4
        )
)

It's true that PHP (or better to say PCRE) doesn't store values of repeated capturing groups for later access (see PCRE docs):

If a capturing subpattern is matched repeatedly, it is the last portion of the string that it matched that is returned.

But in most cases the known token \G does the job. \G 1) matches the beginning of input string (as \A or ^ when m modifier is not set) or 2) starts match from where the previous match ends. Saying that, you have to use it like the following:

preg_match_all('/^\d+|\G(?!^)(,?\d+)\K/', $list, $matches);

See live demo here

or if capturing group doesn't matter:

preg_match_all('/\G,?\d+/', $list, $matches);

by which $matches will hold this (see live demo):

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => ,2
            [2] => ,3
            [3] => ,4
        )

)

Note: the benefit of using \G over the other answers (like explode() or lookbehind solution or just preg_match_all('/,?\d+/', ...)) is that you are able to validate the input string to be only in the desired format ^\d+(,\d+)*$ at the same time while exporting the matches:

preg_match_all('/(?:^(?=\d+(?:,\d+)*$)|\G(?!^),)\d+/', $list, $matches);

Why not just:

$ar = explode(',', $list);
print_r($ar);

Splitting is only an option when the character to split isn't used in the patterns to match itself. I had a situation where a badly formatted comma separated line has to be parsed into any of a number of known options.

i.e. options '1,2', '2', '2,3' subject '1,2,3'.

Splitting on ',' will result in '1', '2', and '3'; only one ('2') of which is a valid match, this happens because the separator is also part of the options.

The naïve regex would be something like '~^(1,2|2|2,3)(?:,(1,2|2|2,3))*$~i', but this runs into the problem of same-group captures.

My "solution" was to just expand the regex to match the maximum number of matches possible: '~^(1,2|2|2,3)(?:,(1,2|2|2,3))?(?:,(1,2|2|2,3))?$~i' (if more options were available, just repeat the '(?:,(1,2|2|2,3))?' bit. This does result in empty string results for "unused" matches.

It's not the cleanest solution, but works when you have to deal with badly formatted input data.

user109764

From http://www.php.net/manual/en/regexp.reference.repetition.php :

When a capturing subpattern is repeated, the value captured is the substring that matched the final iteration.

Also similar thread:

How to get all captures of subgroup matches with preg_match_all()?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!