我使用了 PHP:
$query = 'SELECT column1, column2 as foo, table.column3, table.column4 as foo,
`column5`, `column6` as foo, `table`.`column7`, `table`.`column8` as foo
FROM table';
$query = preg_replace('/^SELECT(.*?)FROM.*$/s', '$1', $query); // To remove the "SELECT" and "FROM table..." parts
preg_match_all('/(?:
(?:`?\w+`?\.)? (?:`)?(\w+)(?:`)? (?:\s*as\s*\w+)?\s*
# ^--TableName-^ ^---ColumnName--^ ^----AsFoo-----^
)+/x',$query, $m);
print_r($m[1]);
输出:
Array
(
[0] => column1
[1] => column2
[2] => column3
[3] => column4
[4] => column5
[5] => column6
[6] => column7
[7] => column8
)
现场演示:http ://www.rubular.com/r/H960NFKCTr
更新:由于您使用了一些“不寻常”但有效的 SQL 表名(例如#__tracktime_projects
:),因此它弄乱了正则表达式。所以为了解决这个问题,我添加了一个包含我们期望的字符的变量,我还添加了i
修饰符以使匹配无大小写:
$query = 'SELECT column1, column2 as foo, table.column3, table.column4 as foo,
`column5`, `column6` as foo, `table`.`column7`, `table`.`column8` as foo, `#__tracktime_projects`.`pr_name` AS project_name, `#wut`
FROM table';
$query = preg_replace('/^SELECT(.*?)FROM.*$/s', '$1', $query); // To remove the "SELECT" and "FROM table..." parts
$allowed = '\w#'; // Adjust this to the names that you expect.
preg_match_all('/(?:
(?:`?['.$allowed.']++`?\.)?
# ^--------TableName--------^
(?:`)?(['.$allowed.']++)(?:`)?
# ^----------ColumnName--------^
(?:\s*as\s*['.$allowed.']++)?\s*
# ^-------------AsFoo------------^
)+
/xi',$query, $m);
print_r($m[1]);
输出:
Array
(
[0] => column1
[1] => column2
[2] => column3
[3] => column4
[4] => column5
[5] => column6
[6] => column7
[7] => column8
[8] => pr_name
[9] => #wut
)
现场演示:http ://www.rubular.com/r/D0iIHJQwB8