tags:

views:

73

answers:

2

Hello,

I have some data similar to this:

aaa1|aaa2|ZZZ|aaa3|aaa4|aaa5|ZZZ|aaa6|aaa7
I want to match all "aaa[0-9]" BETWEEN "ZZZ" (not the ones outside).

So I have some PHP code:

    $string = "aaa1aaa2zzzzaaa3aaa4aaa5zzzzaaa6aaa7";

    preg_match_all("/zzzz.*(aaa[0-9]).*zzzz/", $string, $matches, PREG_SET_ORDER);

    print_r($matches);

But it only outputs:

Array
(
    [0] => Array
        (
            [0] => zzzzaaa3aaa4aaa5zzzz
            [1] => aaa5
        )

)

I want "aaa3", "aaa4" in addition to "aaa5".

Is there a way to do this with 1 call to preg_match_all()?

A: 

I don't think this is possible with a single call. You'll need to do one call to pull out the contents between your delimiters (zzzz) and then another call to pull out all the matching pairs.

if (preg_match('/zzzz(.*?)zzzz/', $string, $matches)) {
    preg_match_all('/(aaa\d)/', $matches[1], $newmatches);
    print_r($newmatches);
} else {
    echo "No match";
}
pix0r
Thanks - unfortunately 1 call is the only option I have. It is a 3rd party system that I know calls preg_match_all but I cannot change the code, only feed in a rule.
Jamie
+1  A: 

Check that the string occurs before one delimiter string (zzzz) but not before two delimiter strings:

$string = "aaa1aaa2zzzzaaa3aaa4aaa5zzzzaaa6aaa7";

preg_match_all("/aaa[0-9](?=.*?zzzz)(?!(?>.*?zzzz).*?zzzz)/", $string, $matches, PREG_SET_ORDER);

print_r($matches);
Jeremy Stein