user3053216
user3053216

Reputation: 809

preg match all get group multiple times

I am trying to get a regular expression to get a subgroup everytime it is found. This is my code:

$string2 = 'cabbba';
preg_match_all('#c(a(b)*a)#',$string2,$result3,PREG_SET_ORDER);
var_dump($result3);

My goal is to get 'b' as a captured group each time (so 3 times). This codes outputs the following:

array (size=1)
  0 => 
    array (size=3)
      0 => string 'cabbba' (length=6)
      1 => string 'abbba' (length=5)
      2 => string 'b' (length=1)

I want it to show 'b' each times it appears, so something like this

array (size=1)
  0 => 
    array (size=3)
      0 => string 'cabbba' (length=6)
      1 => string 'abbba' (length=5)
      2 => array (size=3)
         0 => string 'b' (length 1)
         1 => string 'b' (length 1)
         2 => string 'b' (length 1)

This is a simplified example, in the real code the subpattern 'b' will be different each time, but it follows the same pattern.

Upvotes: 0

Views: 164

Answers (2)

MarcoS
MarcoS

Reputation: 17711

Did you try using a non-greedy modifier for your b*?

$string2 = 'cabbba';
preg_match_all('#c(a(b)*?a)#', $string2, $result3, PREG_SET_ORDER);
var_dump($result3);

Excuse me if it's not what you asked, I'm not sure I really understood your needs...

UPDATE: Sorry, previous answer is wrong, please ignore it...
I'm trying to elaborate a right one...
Just trying something like

preg_match_all('#c(a(?:(b{1}))*a)#', $string2, $result3, PREG_SET_ORDER);

but it doesn't work, either... :-(

UPDATE 2:
See Avinash Raj answer, I think it's quite good...

Upvotes: 0

Avinash Raj
Avinash Raj

Reputation: 174696

This would be possible only through \G anchor.

(?:ca|\G)(b)(?=b|(a))

DEMO

Upvotes: 3

Related Questions