I’m using PHP and I have text like:
first [abc] middle [xyz] last
I need to get what’s inside and outside of the brackets. Searching in StackOverflow I found a pattern to get what’s inside:
preg_match_all('/\[.*?\]/', $m, $s)
Now I’d like to know the pattern to get what’s outside.
Regards!
You can use
preg_splitfor this as:Output:
This allows some surrounding spaces in the output. If you don’t want them you can use:
preg_splitsplits the string based on a pattern. The pattern here is[followed by anything followed by]. The regex to match anything is.*. Also[and]are regex meta char used for char class. Since we want to match them literally we need to escape them to get\[.*\]..*is by default greedy and will try to match as much as possible. In this case it will matchabc] middle [xyz. To avoid this we make it non greedy by appending it with a?to give\[.*?\]. Since our def of anything here actually means anything other than]we can also use\[[^]]*?\]EDIT:
If you want to extract words that are both inside and outside the
[], you can use:which split the string on a
[or a]