Match words then match potentially parenthetical string, then match potential square braced string

I have a script where I need to get three parts out of a text string, and return them in an array. After a couple of trying and failing I couldn’t get it to work.

The text strings can look like this:

Some place
Some place (often text in parenthesis)
Some place (often text in parenthesis) [even text in brackets sometimes]

I need to split these strings into three:

{Some place} ({often text in parenthesis}) [{even text i brackets sometimes}]

Which should return:

1: Some place
2: often text in parenthesis
3: even text in brackets sometimes

I know this should be an easy task, but I couldn’t solve the correct regular expression. This is to be used in PHP.

Thanks in advance!


Try something like this:

$result = preg_match('/
  ^ ([^(]+?)
  (s* ( ([^)]++) ))?
  (s* [ ([^]]++) ])?
  $/x', $mystring, $matches);


Note that in this example, you will probably be most interested in $matches[1], $matches[3], and $matches[5].

Leave a Reply

Your email address will not be published. Required fields are marked *