Preg_split comma, ignore parentheses, PHP

I need to split a string, and I want to avoid separating it with commas in parentheses. So how can I implement this?

Example:

$string = "string1 (sString1, sString2,(ssString1, ssString2)), string2, string3";

result should be:

array(
   [0] => string1 (sString1, sString2,(ssString1, ssString2))
   [1] => string2
   [2] => string3
)
0
source share
2 answers

You will encounter a terrible mess trying to do this with regular expression. It is very simple to iterate over the string characters and perform such a check. Something like the following should work:

<?php

function specialsplit($string) {
    $level = 0;       // number of nested sets of brackets
    $ret = array(''); // array to return
    $cur = 0;         // current index in the array to return, for convenience

    for ($i = 0; $i < strlen($string); $i++) {
        switch ($string[$i]) {
            case '(':
                $level++;
                $ret[$cur] .= '(';
                break;
            case ')':
                $level--;
                $ret[$cur] .= ')';
                break;
            case ',':
                if ($level == 0) {
                    $cur++;
                    $ret[$cur] = '';
                    break;
                }
                // else fallthrough
            default:
                $ret[$cur] .= $string[$i];
        }
    }

    return $ret;
}

var_export(specialsplit("string1 (sString1, sString2,(ssString1, ssString2)), string2, string3"));

/*array (
  0 => 'string1 (sString1, sString2,(ssString1, ssString2))',
  1 => ' string2',
  2 => ' string3',
)*/

Note that this method is much harder to do if you have more than a single-character string to split.

+6
source

I tried my best ... it might work for you.

<?php
$string = "string1 (sString1, sString2,(ssString1, ssString2)), string2, string3";
$pattern = '#(?<=\)),#';
$out=preg_split($pattern,$string);
$more=split(",",array_pop($out));
$res=array_merge($out,$more);
echo "<pre>";
print_r($res);

?>
0
source

All Articles