5

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! :)

4
  • Are your curly brackets guaranteed to be balanced? Commented Jun 13, 2012 at 22:58
  • @ghoti Yes, they are guaranteed to be balanced. Commented Jun 13, 2012 at 23:01
  • @Vulcan I have added info about what I've tried to the original post. Commented Jun 13, 2012 at 23:01
  • Are the top-level curly brackets always separated by a single space? Commented Jun 13, 2012 at 23:08

2 Answers 2

5

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];
Sign up to request clarification or add additional context in comments.

2 Comments

Edit: It works and I get it, thank you very much, sir! Now I only need to understand what exactly this regexp does. :)
@moskalak, the elements in $matches[1]. Also welcome to SO, here best way to thank is by up voting. ;-)
4
$x="foo {bar {baz}} whee";
$re="/(^[^{]*){(.*)}([^}]*)$/";
print preg_replace($re, "\\1\\2\\3", $x) . "\n";'

returns:

foo bar {baz} whee

1 Comment

Thank you for this proposition. It would be great, but it returns a string stripped of top-level brackets while I really need to create an array in which every string bracketed at top-level would be another entry.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.