我试图从mysql命令标识符和别名BY和最亲密的问题,它可以帮助我是Removing aliases from a SQL select statement, using C# and regular expressions的preg_match提取标识符和别名
function test($orderby)
{
if(preg_match('/(?<field>.*)(?:\s*|\s+AS\s+)?(?<alias>\w*)?/i', $orderby, $matches)){
unset($matches[1]);
unset($matches[2]);
echo '<pre>'.htmlspecialchars(print_r($matches,true)).'</pre>';
}else{
echo '$orderby doest not matches';
}
}
test("field");
工作
Array
(
[0] => field
[field] => field
[alias] =>
)
test("table.field");
工作
Array
(
[0] => table.field
[field] => table.field
[alias] =>
)
test("CONCAT(table.field1, ' ', table.field2) AS alias");
不工作
Array
(
[0] => CONCAT(table.field1, ' ', table.field2) AS alias
[field] => CONCAT(table.field1, ' ', table.field2) AS alias
[alias] =>
)
test("table.field alias");
打印
Array
(
[0] => table.field alias
[field] => table.field alias
[alias] =>
)
我需要例如3 [field] => CONCAT(table.field1, ' ', table.field2)
和[alias] => alias
在和实例4 [field] => table.field
和[alias] => alias
我想要做的是
/
(?<field>.*) #identifier
(?:\s*|\s+AS\s+)? # without spaces (examples 1 and 2), spaces (example 4) OR 'AS' (example 3)
(?<alias>\w*)? #alias
/i
我做错了什么? 在此先感谢。
不要使用正则表达式来做到这一点,请使用适当的SQL语法分析。 –