分解 php 中的字符串,不包括大括号内的 ', '

Explode a string in php excluding the ', ' within braces

我有一串这样的-

$str = "field1.id as field1, 
       DATE_SUB(field2, INTERVAL (DAYOFMONTH(field2)-1) DAY) as field2,   
       field3.name as field3";

需要 explode 将其放入 , 数组中,如下所示:

$requiredArray = array(
  0 => field1.id as field1,
  1 => DATE_SUB(field2, INTERVAL (DAYOFMONTH(field2)-1) DAY) as field2
  2 => field3.name as field3
);

我试过爆炸但它不起作用:

$requiredArray = explode(', ', $str); 
// doesn't work as "DATE_SUB(field2, INTERVAL ..." also gets exploded

任何 trick/ideas?

试试这个:

preg_match_all('~(.*)[^(],?~', $str, $matches);

请试试这个

$str = "field1.id as field1, 
       DATE_SUB(field2, INTERVAL (DAYOFMONTH(field2)-1) DAY) as field2,   
       field3.name as field3";

$buffer = '';
$stack = array();
$depth = 0;
$len = strlen($str);
for ($i=0; $i<$len; $i++) {
    $char = $str[$i];
    switch ($char) {
    case '(':
        $depth++;
        break;
    case ',':
        if (!$depth) {
            if ($buffer !== '') {
                $stack[] = $buffer;
                $buffer = '';
            }
            continue 2;
        }
        break;
    case ' ':
        if (!$depth) {
             $buffer .= ' ';
            continue 2;
        }
        break;
    case ')':
        if ($depth) {
            $depth--;
        } else {
            $stack[] = $buffer.$char;
            $buffer = '';
            continue 2;
        }
        break;
    }
    $buffer .= $char;
}
if ($buffer !== '') {
    $stack[] = $buffer;
}
echo "<pre>";
print_r($stack);
echo "</pre>";