Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP, regex and multi-level curly brackets

I've got a string which consists of few sentences which are in curly brackets that I want to remove. That would be not that hard to do (as I know now.), but the real trouble is it's multilevel and all I want to strip is the top level brackets and leave everything inside intact. It looks something like this:

{Super duper {extra} text.} {Which I'm really {starting to} hate!} {But I {won't give up} so {easy}!} {Especially when someone is {gonna help me}.}

I want to create an array that would consist of those four entries:

Super duper {extra} text.
Which I'm really {starting to} hate!
But I {won't give up} so {easy}!
Especially when someone is {gonna help me}.

I have tried two ways, one was preg_split which didn't do much good:

$key = preg_split('/([!?.]{1,3}\} \{)/',$key, -1, PREG_SPLIT_DELIM_CAPTURE);
$sentences = array();

for ($i=0, $n=count($key)-1; $i<$n; $i+=2) {
$sentences[] = $key[$i].$key[$i+1]."<br><br>";
}

Another one was using preg_match_all which was quite good until I realized I had those brackets multilevel:

$matches = array();
$key = preg_match_all('/\{[^}]+\}/', $key, $matches);
$key = $matches[0];

Thanks in advance! :)

like image 711
moskalak Avatar asked Jun 13 '12 22:06

moskalak


1 Answers

You can use a recursive expression like this:

/{((?:[^{}]++|(?R))*+)}/

The desired results will be in the first capturing group.

Usage, something like:

preg_match_all('/{((?:[^{}]++|(?R))*+)}/', $str, $matches);
$result = $matches[1];
like image 189
Qtax Avatar answered Oct 20 '22 00:10

Qtax