tags:

views:

276

answers:

1

I have a regular expression like this (much simplified):

^(ab)*$

And am matching against this:

abababababababab

When I run it through preg_match:

preg_match('/$(ab)*$/', 'abababababababab', $matches);
print_r($matches);

I get this:

Array
(
    [0] => abababababababab
    [1] => ab
)

Wheras I expect this:

Array
(
    [0] => abababababababab
    [1] => ab
    [2] => ab
    [3] => ab
    [4] => ab
    [5] => ab
    [6] => ab
    [7] => ab
    [8] => ab
}

How can I get what I expect?

(Note that the subexpression could be more complicated, e.g. ([aA][bB]), and I want the matched expressions in their order in the subject.)

+4  A: 

Do it by using preg_match_all like this:

preg_match_all('/(ab)/', 'abababababababab', $matches);
print_r($matches);

Remember that preg_match only provides the first match and that preg_match_all has the same functionality, but returns all. Also note that now the regular expression has changed. If you use the asterisk, it'll likely consume the entire string on the first match. You could, however, try something like (ab)*? to make it nongreedy.

Evan Fosmark
This works great. Thanks!
strager
No problem. Good luck with whatever it is you're trying to accomplish, strager. ;-)
Evan Fosmark