douyimiao1993 2017-04-19 03:53
浏览 57
已采纳

使用Regex [PHP]拆分SQL列名及其别名中的任何一个

Using Regex I want to separate the column names (if any) from their aliases. As I mentioned below, I created an expression but it does not work without quotes.

Thank you !

(?<nameFull>               #nameRegex
 (?<name>[^"'`]+)          #name
 (?<nameQoute>["'`]+)?      #name Qoute
)
(?<aliasFull>               #aliasRegex
 \s+                        #before Alias WhiteSpace
 (?<AS>AS\s+)?              #AS Is match or Not match
 (?<aliasQoute>["'`])?      #alias Qoute
 (?<alias>[^"'`]+)          #alias
)?

You can also see the test I made with this link.

  • 写回答

1条回答 默认 最新

  • dtqpw68806 2017-04-19 05:45
    关注

    Here is a regex matching your needs :

    ^\W?(?<table>[\w-]+\.)?(?<name>[\w-]+)\W?(\W+as\W+)?(?<alias>[\w-]+)?\W?$

    Test this regular expression online

    PHP snippet

    $re = "/^\W?(?<table>[\w-]+\.)?(?<name>[\w-]+)\W?(\W+as\W+)?(?<alias>[\w-]+)?\W?$/i";
    
    $array = [
        "columnam-e as myalias",
        "table.columnam-e as myalias",
        '"column" AS "mycolumn"',
        "'column' AS 'mycolumn'",
        "'table.column' AS 'mycolumn'",
        "`column` AS `mycolumn`",
        "columnam-e mycolumn",
        "colunmanesingle"
    ];
    
    foreach ($array as $i => $value) {
    
        preg_match($re, $value, $matches);
    
        $name = $matches['name'];
        $table = NULL;
        $alias = NULL;
    
        if(array_key_exists('table', $matches)) {
          $table =  $matches['table'];
        }
        if(array_key_exists('alias', $matches)) {
          $alias =  $matches['alias'];
        }
    
        printf("%s=> table: %s, name: %s, alias: %s", $value, $table, $name, $alias);
    }
    

    Test this PHP snippet online

    展开全部

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部