下面的函数接受一个函数并返回col->table映射作为数组。
例如
$query = “SELECT a.id AS a_id, b.id b_id FROM atable AS a, btable b”
$cols = queryAlias($query);
print_r($cols);
返回
数组
(
[a] => atable
[b] => btable
)
我不能保证它是完美的,但是这个函数从未进入生产环境,因为我最终使用了mysqli方法。
享受
-Jorge
/**
* 接受一个查询并返回alias->table映射。
*
* @param string $query
* @return alias映射数组
*/
function queryAlias ( $query ) {
//将所有内容转换为小写,我们忽略大小写
$substr = strtolower($query);
//移除任何子查询
$substr = preg_replace ( ‘/\(.*\)/’, ”, $substr);
//移除任何特殊字符
$substr = preg_replace ( ‘/[^a-zA-Z0-9_,]/’, ‘ ‘, $substr);
//移除任何空格
$substr = preg_replace(‘/\s\s+/’, ‘ ‘, $substr);
//获取FROM之后的所有内容
$substr = strtolower(substr($substr, strpos(strtolower($substr),‘ from ‘) + 6));
//去除任何额外的命令
$substr = preg_replace(
Array(
‘/ where .*+$/’,
‘/ group by .*+$/’,
‘/ limit .*+$/’ ,
‘/ having .*+$/’ ,
‘/ order by .*+$/’,
‘/ into .*+$/’
), ”, $substr);
//移除任何JOIN修饰符
$substr = preg_replace(
Array(
‘/ left /’,
‘/ right /’,
‘/ inner /’,
‘/ cross /’,
‘/ outer /’,
‘/ natural /’,
‘/ as /’
), ‘ ‘, $substr);
//用逗号替换JOIN语句
$substr = preg_replace(Array(‘/ join /’, ‘/ straight_join /’), ‘,’, $substr);
$out_array = Array();
//按FROM语句分割
$st_array = split (‘,’, $substr);
foreach ($st_array as $col) {
$col = preg_replace(Array(‘/ on .*+/’), ”, $col);
$tmp_array = split(‘ ‘, trim($col));
//哦不,出错了,让我们继续
if (!isset($tmp_array[0]))
continue;
$first = $tmp_array[0];
//如果设置了“AS”,让我们包含它,如果没有,那么这个表可能没有别名。
if (isset($tmp_array[1]))
$second = $tmp_array[1];
else
$second = $first;
if (strlen($first))
$out_array[$second] = $first;
}
return $out_array;
}