-5

I have a string:

abc{def}ghij{kl{mn}o{pq}}r{s{t{u{v}}w}}xyz

Goal is to extract everything within brackets:

1. def
2. kl{mn}o{pq}
3. mn
4. pq
5. s{t{u{v}}w}
6. t{u{v}}w
7. u{v}
8. v

Looking for any solution, wether regex or loops.

EDIT:

Okay, since this started to getting some temper, here's what I've tried:

preg_match("/(\{[^\{]+\})+/", $str, $matches); // matches only first occurrence
preg_match_all("/(\{[^\{\}]+\})+/", $str, $matches); // this matches only the final level occurrences

And actually out of ideas how this could be achieved.

So for now, my toughest obstacle is to find all occurrences on the 1st level. This way I could recursively dig down the string and retrieve all subsets I need.

Aleksandr Makov
  • 2,820
  • 3
  • 37
  • 62
  • 3
    Have you tried solving this problem yourself? – Blender Jan 25 '13 at 23:50
  • 1
    StackOverflow is not the proper place for this question. We do not write your code for you. You need to do your own coding and if you aren't sure why something is not working as expected, post the code with an explanation of what you were expecting it to do, and what it is actually doing including all error messages. See [ask advice](http://stackoverflow.com/questions/ask-advice). – John Conde Jan 25 '13 at 23:51
  • possible duplicate of [Removing nested parentheses using regex in PHP](http://stackoverflow.com/questions/12762778/removing-nested-parentheses-using-regex-in-php) – mario Jan 25 '13 at 23:52
  • Thanks, opinions received. Editing. – Aleksandr Makov Jan 26 '13 at 00:03

1 Answers1

4

you could go through the string and put the position of { onto the stack making a match of } pop from that stack.

You will then get the list, however in a different order:

abc{def}ghij{kl{mn}o{pq}}r{s{t{u{v}}w}}xyz
  1. def
  2. mn
  3. pq
  4. kl{mn}o{pq}
  5. v
  6. u{v}
  7. t{u{v}}w
  8. s{t{u{v}}w}

This would be a solution with a loop.

hakre
  • 193,403
  • 52
  • 435
  • 836
  • Thanks. That's simple and elegant. However, I have to try it out since the real input string is quite large and tags are multiple chars long. – Aleksandr Makov Jan 26 '13 at 00:11
  • This method should work very well even with large strings. It's possibly even more efficient than a regex-only solution. BTW. for locating the next interesting character you can use [`preg_match`](http://php.net/preg_match) with the `$offset` parameter *and* the `PREG_OFFSET_CAPTURE` flag. – hakre Jan 26 '13 at 00:19
  • 1
    @AleksandrMakov: You can find some example code for what I outlined in my yesterdays comment here: http://eval.in/7578 – hakre Jan 26 '13 at 12:39