Mortaza Faryabi Mortaza Faryabi - 4 months ago 13
PHP Question

how can i split the string with the cammas that are not embeded in braces , brackets and qutations from a string with php

--eddited--

how can i split the string with the cammas that are not embeded in braces , brackets and qutations from a string with php

Jan Jan
Answer

One way would be to use lookarounds:

<?php

$data = <<<DATA
func('name','family,address') , "lorem ipsom, is a..." , ['name','part']
DATA;

$regex = '~(?<=\ ),(?=\h)~';

$parts = preg_split($regex, $data);
print_r($parts);
?>


See a working demo on ideone.com.

Even better yet would be a (*SKIP)(*FAIL) mechanism:

<?php

$data = <<<DATA
func('name','family,address') , "lorem ipsom, is a..." , ['name','part']
DATA;

$regex = '~
            (\w+\([^)]+\)
            |
            "[^"]+"
            |
            \[[^]]+\]
            (*SKIP)(*FAIL))
            |
            \h*,\h*
        ~x';

$parts = preg_split($regex, $data, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
print_r($parts);
?>

See a demo for this one on ideone.com as well.