Jan
Jan

Reputation: 43189

How to grab recursive matches in groups?

Imagine, I have the following string:

$str = "[block]teststring [block]teststring123  [/block][/block]";

I'd like to get the values in the [block] elements (teststring, teststring123). I know I could do sth. like:

<?php
$str = "[block]teststring [block]teststring123  [/block][/block]";

$regex = '/\[block\]([^\[\]]+)/';
preg_match_all($regex, $str, $matches);
print_r($matches);
// outputs array(array("[block]teststring ", "[block]teststring123  "),
//               array("teststring ", "teststring123  "));
?>

However, as I am learning more and more about regular expressions, I thought about using a recursion:

$regex = '/\[block\]([^\[\]]+)(?R)?/';

This works insofar as the whole string is matched, but then I am unable to access the submatches ([block]teststring, [block]teststring123). How can this be done via a regex in PHP?

Upvotes: 1

Views: 33

Answers (1)

anubhava
anubhava

Reputation: 786091

You can use this recursive regex:

\[block\]([^][]+)(?1)

(?1) recurses the 1st sub-pattern.

RegEx Demo

Code:

$re = '~\[block\]([^][]+)(?1)~'; 
$str = "[block]teststring [block]teststring123  [/block][/block]"; 

preg_match_all($re, $str, $matches);
print_r($matches);

Upvotes: 1

Related Questions