Tuesday, 20 August 2013

PHP Regex: get substrings from string with parentheses, brackets and hyphen

PHP Regex: get substrings from string with parentheses, brackets and hyphen

Regex is not my strongest suit and I'm having a bit of trouble with this
situation.
I have the following string:
locale (district - town) [parish]
I need to extract the following information: 1 - locale 2 - district 3 - town
And I have these solutions:
1 - locale
preg_match("/([^(]*)\s/", $input_line, $output_array);
2 - district
preg_match("/.*\(([^-]*)\s/", $input_line, $output_array);
3 - town
preg_match("/.*\-\s([^)]*)/", $input_line, $output_array);
And these seem to work fine. However, the string may be presented like any
of these:
localeA(localeB) (district - town) [parish]
locale (district - townA(townB)) [parish]
locale (district - townA-townB) [parish]
Locale can also include parentheses of its own. Town can include
parentheses and/or an hyphen of its own.
Which makes it difficult to extract the right information. In the 3
scenarios above I would have to extract:
localeA(localeB) + district + town
locale + district + townA(townB)
locale + district + townA-townB
I find it hard to deal with all these scenarios. Can you help me out?
Thanks in advance

No comments:

Post a Comment