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

自作多情 提交于 2019-12-12 19:04:22

问题


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
]

回答1:


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

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

https://regexr.com/3qudi




回答2:


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




回答3:


For your example, if you don't want to use regex and want to stick with the explode() function you are already using, you could simply replace all instances of ', ' with ',', then break the string in parts by , (followed by a space) instead of just the comma.

This makes it so things inside the brackets don't have the explode delimiter, thus making them not break apart into the array.

This has an additional problem, if you had a string like '==', 'test-taco', this solution would not work. This problem, along with many other problems probably, can be solved by removing the single quotes from the separate strings, as ==, test-taco would still work.

This solution should work if your strings inside brackets are valid PHP arrays/JSON string

$str = "'==', ['abc', 'xyz'], 1";
$str = str_replace("', '", "','", $str);
$str = explode(", ", $str);

Though I recommend regex as it may solve some underlying issues that I don't see.

Output is:

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


来源:https://stackoverflow.com/questions/50820944/php-split-a-string-by-comma-but-ignoring-anything-inside-square-brackets

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!