Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
]
like image 786
Amitoz Deol Avatar asked May 22 '26 16:05

Amitoz Deol


2 Answers

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

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

https://regexr.com/3qudi

like image 135
offwhite Avatar answered May 25 '26 06:05

offwhite


For your example data you might use preg_split and use a regex to match a comma or match the part with the square brackets and then skip that using (*SKIP)(*FAIL).

,|\[[^]]+\](*SKIP)(*FAIL)

$pattern = '/,|\[[^]]+\](*SKIP)(*FAIL)/';
$string = "'==', ['abc', 'xyz'], 1";
$result = preg_split($pattern, $string);
print_r($result);

That would give you:

Array
(
    [0] => '=='
    [1] =>  ['abc', 'xyz']
    [2] =>  1
)

Demo

like image 28
The fourth bird Avatar answered May 25 '26 05:05

The fourth bird



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!