AeronMan
AeronMan

Reputation: 3

Preg_match_all repeated group

this is my string:

zzzzzzz-------eh="koko"------eh="zizi"--------eh="mimi"--------xxxxxx

i need a reg-expression to extract koko, zizi and mimi

but eh='zizi' is optional: so if it doesn't exist like in :

zzzzzzz----------eh="koko"-----------------eh="mimi"----------xxxxxx

i should get only koko and mimi.

the '---' are some text.

i tried

preg_match_all('#zzzzzzz(.*eh="([^"]*)"){2,3}.*xxxxxx#Uix',  $strg , $out, PREG_SET_ORDER);

but it doesn't work.

note: the whole thing is like :

zzzzzzz--...--xxxxxxzzzzzzz--...--xxxxxxzzzzzzz--...--xxxxxxzz...

i need them grouped

like :

array():{
         [0]:array():{
                       [0]:"zizi",
                       [1]:"mimi",
                       [2]:"koko",
                     },
          [1]:array():{
                       [0]:"zizi",
                       [1]:"koko",
                     },
         [2]:array():{
                       [0]:"zizi",
                       [1]:"fofo",
                       [2]:"bingo",
                     },   
}

Upvotes: 0

Views: 445

Answers (3)

Toto
Toto

Reputation: 91385

How about:

$str = 'zzzzzzz-------eh="koko"------eh="zizi"--------eh="mimi"--------xxxxxxzzzzzzz----------eh="koko"-----------------eh="mimi"----------xxxxxx';
$arr = preg_split('/(?<=x)(?=z)/', $str);
foreach($arr as $s) {
    preg_match_all('/"([^"]+)"/', $s, $out);
    $arr_out[] = $out[1];
}
print_r($arr_out);

output:

Array
(
    [0] => Array
        (
            [0] => koko
            [1] => zizi
            [2] => mimi
        )

    [1] => Array
        (
            [0] => koko
            [1] => mimi
        )

)

Upvotes: 0

Ibrahim Najjar
Ibrahim Najjar

Reputation: 19423

Why not just:

preg_match_all('/(?<=eh=")([^"]+)(?=")/', $strg, $out, PREG_SET_ORDER);

Regex101 Demo

Upvotes: 1

anubhava
anubhava

Reputation: 784998

This can be solved by capturing all strings preceded by =" until a " is found:

$s='zzzzzzz-------eh="koko"------eh="zizi"--------eh="mimi"--------xxxxxx';
if (preg_match_all('~(?<==")[^"]*~', $s, $arr))
   print_r($arr);

OUTPUT:

Array
(
    [0] => Array
        (
            [0] => koko
            [1] => zizi
            [2] => mimi
        )

)

Upvotes: 0

Related Questions