3

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?

jitendrapurohit
  • 9,435
  • 2
  • 28
  • 39

2 Answers2

4

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>";
Arzon Barua
  • 494
  • 7
  • 11
-1

Try this :

preg_match_all('~(.*)[^(],?~', $str, $matches);
kamal pal
  • 4,187
  • 5
  • 25
  • 40