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
]
yeah, regex - select all commas, ignore in square brakets
/[,]+(?![^\[]*\])/g
https://regexr.com/3qudi
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With