问题
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