Regular expressions are not parsers.
For a lightweight solution I suggest you use the JSON parser, e.g., like this:
$tree = json_decode('["root","'.
preg_replace('/\[\{(\w+):/',
'",["\1","',
str_replace(array('\\', "\n", '"', '}]'),
array('\\\\', '\n', '\"', '"],"'),
$str).
'"]'));
For this input (your example):
$str = 'Hi [{tagname:content}] [{tag1:xnkudfdhkfujhkdjki diidfo now nested tag
[{tag2: more data here}] kj udf}]';
you get this output:
$tree = array(
0 => "root",
1 => "Hi ",
2 => array(
0 => "tagname",
1 => "content"
),
3 => " ",
4 => array(
0 => "tag1",
1 => "xnkudfdhkfujhkdjki diidfo now nested tag\n",
2 => array(
0 => "tag2",
1 => " more data here"
),
3 => " kj udf"
),
5 => ""
);
The tag name is element 0
of each subtree (I added an arbitrary "root"
tag). I assumed tag names to be a simple \w+
. That should be changed to reflect allowed tag names. As you see there may be extra empty strings in the parse tree, but you can easily get rid of them.
I know, your question was about PCREs, but it was a bit like asking for the right hammer to turn a screw.
BTW, parsers built on recursive regex engines have one theoretical disadvantage that can become quite real: since they must rescan every input element as many times as its depth in the tree, their worst case time complexity, assuming no backtracking, is O(n2).