user606521
user606521

Reputation: 15454

php regular expression - how to separate repetition of subpattern in results

I have following regular expression:

preg_match('/some text \d ([\d\,\s]*[A-Z0-9]\, [A-Za-ząćęłńóśźżĄĆĘŁŃÓŚŹŻ\s]*){0,5}/',$text,$results);

Inside there is subpattern: ([\d\,\s]*[A-Z0-9]\, [A-Za-ząćęłńóśźżĄĆĘŁŃÓŚŹŻ\s]*) and I want to match it from 0 up to 5 times. But I would like to have each of the match of this subpattern to be separated from others in the $result array. - How I can do it?

For my result is (I changed strings for this example):

0 => string 'some text pattern1 pattern2 pattern3 pattern4 pattern5' (length=376)
1 => string 'pattern5' 

So it matches subpattern 5 times but only last one is separated in array...

Upvotes: 1

Views: 339

Answers (2)

Toto
Toto

Reputation: 91498

I'd do that with several steps.

According to your simplified string:

$text = "some text pattern1 pattern2 pattern3 pattern4 pattern5";
if (preg_match('/^some text /', $text)) {
    $text = preg_replace('/^some text /', '', $text);
    preg_match_all('/(pattern\d)/', $text, $m);
    print_r($m);
}

output:

Array
(
    [0] => Array
        (
            [0] => pattern1
            [1] => pattern2
            [2] => pattern3
            [3] => pattern4
            [4] => pattern5
        )

    [1] => Array
        (
            [0] => pattern1
            [1] => pattern2
            [2] => pattern3
            [3] => pattern4
            [4] => pattern5
        )

)

Upvotes: 2

Jon
Jon

Reputation: 437604

Not possible AFAIK. You would have to manually repeat the pattern in the regular expression.

Upvotes: 2

Related Questions