【问题标题】:preg_match extract identifier and aliaspreg_match 提取标识符和别名
【发布时间】:2016-03-07 10:47:09
【问题描述】:

我正在尝试从 mysql ORDER BY 中提取标识符和别名,它可以帮助我的最接近的问题是 Removing aliases from a SQL select statement, using C# and regular expressions

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] =&gt; CONCAT(table.field1, ' ', table.field2) AND [alias] =&gt; alias 和示例 4 [field] =&gt; table.field AND [alias] =&gt; 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 解析。

标签: php mysql sql regex preg-match


【解决方案1】:

此模式适用于您的所有示例:

/(?<field>.*?)((?:\s+|\s+AS\s+)(?<alias>\w+))?$/i
            │ │     │          ┊          │ │┊│
            1 2     3          4          5 267

1) Added   not-greedy operator;
2) Added   capturing group for sub-groups AS/alias;
3) Changed zero-or-more to one-or-more (at least one space is needed);
4) Removed zero-or-one for subgroup AS (at least one space is needed);
5) Changed zero-or-more to one-or-more (at least one char is needed);
6) Moved   zero-or-more from sub-group alias to group 2);
7) Added   end-of-line anchor.

eval.in demo

创建了新的捕获组,因此您还必须取消设置$matches[3]

unset( $matches[1], $matches[2], $matches[3] );

由于我们添加了endline锚点,我建议你在函数的开头添加这一行:

$orderby = trim( $orderby );

【讨论】:

  • 哇,高质量的答案。感谢您的努力!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-15
  • 2012-02-11
  • 2012-02-26
  • 2020-08-20
  • 1970-01-01
相关资源
最近更新 更多