在sql查询中帮助使用正则表达式逗号

时间:2010-10-25 12:10:20

标签: php sql regex

我有一个SQL查询,如:

select column1 as a, DECODE(x, 1, x1, 2, x2) as column2, 
    DECODE(y, 1, y1, 2, y2) as column3 from test

我想选择以下逗号(用**,**表示):

select a as column1 **,** DECODE(x, 1, x1, 2, x2) as column2 **,** 
    DECODE(y, 1, y1, 2, y2) as column3 from test

我正在使用/(?!(.*\))),|,(?=.*\()/gs,但您如何在http://gskinner.com/RegExr/中看到第一个DECODE中的逗号也被选中。我需要在此代码中使用的select中的解析列的正则表达式:

$select = substr($sql, 6, strpos($sql, "from") - 6);
$parts = preg_split('/(?!(.*\))),|,(?=.*\()/s', $select);

$columns = array();
foreach($parts as $p) {
    @list($id, $alias) = preg_split('/( as )/', $p);
    $columns[trim($id)] = trim($alias);
}

1 个答案:

答案 0 :(得分:0)

试试这个:

<?php

$sql = "select a as column1, DECODE(x, 1, x1, 2, x2) as column2, DECODE(y, 1, y1, 2, y2) as column3 from test";

$select = substr($sql, 6, strpos($sql, "from") - 6);
$select .=',';
$parts = preg_split('/ as (.*?),/s', $select, NULL, PREG_SPLIT_DELIM_CAPTURE);
$columns = array();
for($i=0; $i<count($parts)-1; $i+=2) {
  $columns[trim($parts[$i])] = $parts[$i+1];
}
print_r($columns);

?>

更新

对于更复杂的查询,您应该使用SQL解析器。