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

旧街凉风 提交于 2019-12-22 10:30:54

问题


I have a string of this-

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

Need to explode this into array with , as this:

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

I've tried with explode but it doesn't works:

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

Any trick/ideas?


回答1:


Please try this

$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>";



回答2:


Try this :

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


来源:https://stackoverflow.com/questions/37183910/explode-a-string-in-php-excluding-the-within-braces

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