php - preg_match 提取标识符和别名

标签 php mysql sql regex preg-match

我正在尝试从 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 别名"); 不起作用

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) AND [alias] => alias 并在示例中4 [field] => table.field AND [alias] => 别名

我想做的是

/
(?<field>.*)             #identifier
(?:\s*|\s+AS\s+)?        # without spaces (examples 1 and 2), spaces (example 4) OR 'AS' (example 3)
(?<alias>\w*)?           #alias
/i

我做错了什么? 提前致谢。

最佳答案

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

/(?<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.

3v4l.org demo

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

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

由于我们添加了结束行 anchor ,因此我建议您在函数的开头添加此行:

$orderby = trim( $orderby );

关于php - preg_match 提取标识符和别名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35841744/

相关文章:

php - 从 CLI OSX 退出 PHP

php - 查询架构以获取用户关注的帖子

php - 如何使用 $_POST 保存 contentEditable ="true"的 Div?

MySQL (MariaDB - 10.0.16-MariaDB-1 (Debian) 奇怪的性能问题

mysql - 如何比较两个表并显示每个差异

sql - 汇总总计

sql - 使用 T-SQL/MS-SQL 将字符串附加到现有表格单元格的最简单方法是什么?

php - 序列化 POST 数组,以便 Cake PHP 可以插入 MySQL 数据库

python - 在python中执行查询之前设置游标对象的限制

php - 如何在 MySQL 中用零填充数字?