-2

I have the following PHP string:

$str = "a b [[c], [d] then [e]] followed by [f] then [g]";

I'm trying to write 2 expressions in PHP; one to extract the [c], [d], [e] (including the square brackets) and a second regex to extract the [f] and [g] (including brackets).

Bonus points for anyone who can do it with whitespace added before or after a square bracket.

Does anyone have any ideas?

Thanks :)

Avinash Raj
  • 172,303
  • 28
  • 230
  • 274

1 Answers1

0

You can try with this simple and readable regex (for two levels only and balanced brackets):

(?|(?<=\[)[^\[\]]*(?<nested>\[[^\[\]]+\])[^\[\]]*|(?<=(?!\A)\G)(\[[^\[\]]*\])[^\[\]]*(?=(?:[^\[\]]*\[[^\[\]]+\])*\])|(?<=(?!\A)\G)[^\[\]]*(\[[^\[\]+]\])[^\[\]]*(?=\]))|(?<simple>\[[^\[\]]+\])

DEMO

I'm pretty sure, that there is (probably better) way to do that without regex, but this is how I would do that with regex. Probably there is also better way to do that with regex :D

About whitspaces before and after brackets, I don't know what you mean: inside or outside brackets? add whitspaces, or match whitspaces if its occour before or after bracket?

m.cekiera
  • 5,365
  • 5
  • 21
  • 35