繁体   English   中英

preg_match提取标识符和别名

[英]preg_match extract identifier and alias

我正在尝试从mysql ORDER BY中提取标识符和别名,最近的问题可以帮助我的问题是,使用C#和正则表达式从SQL select语句中删除别名

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 AND [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

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

此模式适用于所有示例:

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

评估演示

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

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

由于我们添加了终点锚,因此建议您在函数开头添加以下行:

$orderby = trim( $orderby );

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM