1

I need some regex help. I want to explode as string by a given delimiter (this could change) but in this case a comma. But only, if that comma is not in between square brackets

Here is my example string :

name:in:['john','jane'],name:in:['doe']

My desired outcome :

Array(
    [0] => name:in:['john,'jane']
    [1] => name:in['doe']
)

I feel i'm close but this is not quite working :

$filters = preg_split("~$delimiter(?![^[]]*\))~", $filters);

Current output :

Array
(
    [0] => name:in:['john'
    [1] => 'jane']
    [2] => name:in:['doe']
)

It would be great if someone could help, but also explain the regex by breaking it down into its parts.

Frank
  • 243
  • 1
  • 2
  • 14
  • 1
    Should be `\]`, not `\)` i.e. `preg_split("~$delimiter(?![^[]*\])~", $filters)` https://3v4l.org/srmQn – Nick Mar 20 '19 at 12:12
  • That's spot on Nick. Would be great if you could post it as an answer with a description of the parts, then happy to accept ! – Frank Mar 20 '19 at 12:22
  • I can't post an answer as the question has been closed as a duplicate, but there's a good explanation of how this regex works (for `()` instead of `[]`) here: https://stackoverflow.com/questions/9030036/regex-to-match-only-commas-not-in-parentheses/9030062#9030062 – Nick Mar 20 '19 at 21:53
  • I somewhat disagree with this being marked as a duplicate. Regex can be very fiddly and and the first 'duplicate' is a different programming language. Anyway, regex is regex, and stackoverflow gods rule us all. Thanks @nick – Frank Mar 21 '19 at 11:53

0 Answers0