Tim van Dalen
Tim van Dalen

Reputation: 1471

Capturing repeated group in Regex PHP

I'm trying to capture repeated groups in a PHP regular expression.

The expression I'm using is: (?:.*\s|^)@\[(\d+)\], which would match stuff like:

some text here @[2] some more text and return 2 in the matches.

Now I'd like to match:

some text here @[2] some more text @[3] more text and return [2, 3]. Right now, I can only get it to return 3 (the last element) with this expression: (((?:.*\s|^)@\[(\d+)\])+).

I've read this and this, but I couldn't get those working with preg_match or preg_match_all.

Any input on this would be appreciated.

Upvotes: 1

Views: 1517

Answers (1)

Aurelio De Rosa
Aurelio De Rosa

Reputation: 22152

I suggest this simpler solution:

$string = 'some text here @[2] some more text @[3] more text';
preg_match_all('/@\[(\d+)\]/', $string, $matches);
$matches = $matches[1];
$result = '[' . implode(', ', $matches) . ']';
echo $result; // [2, 3]

Upvotes: 1

Related Questions