Search code examples
phplaravellaravel-5php-7text-parsing

PHP: Split a string by comma(,) but ignoring anything inside square brackets?


How do I split a string by , but skip the one that's inside an array

String - "'==', ['abc', 'xyz'], 1"

When I do explode(',', $expression) it's giving me 4 item in array

array:4 [
   0 => "'=='"
   1 => "['abc'"
   2 => "'xyz']"
   3 => 1
]

But I want my output to be -

array:3 [
   0 => "'=='"
   1 => "['abc', 'xyz']"
   2 => 1
]

Solution

  • yeah, regex - select all commas, ignore in square brakets

    /[,]+(?![^\[]*\])/g
    

    https://regexr.com/3qudi