phpregexsplitdelimited

Split string on pipes which are not between square braces


I have this string:

EXAMPLE|abcd|[!PAGE|title]

I want to split it like this:

Array
(
    [0] => EXAMPLE
    [1] => abcd
    [2] => [!PAGE|title]
)

How to do it?


Solution

  • DEMO

    If you don't need anything more than you said, is like parsing a CSV but with | as separator and [ as " so: (\[.*?\]+|[^\|]+)(?=\||$) will do the work I think.

    EDIT: Changed the regex, now it accepts strings like [asdf]].[]asf]

    Explanation:

    1. (\[.*?\]+|[^\|]+) -> This one is divided in 2 parts: (will match 1.1 or 1.2)
      1.1 \[.*?\]+ -> Match everything between [ and ]
      1.2 [^\|]+ -> Will match everything that is enclosed by |
    2. (?=\||$) -> This will tell the regular expression that next to that must be a | or the end of the string so that will tell the regex to accept strings like the earlier example.