dpa84373 2012-06-23 15:00
浏览 41
已采纳

PHP Regex拆分SQL字段列表

I'm looking for a regular expression to split a field list from an SQL SELECT statement.

I have already extracted the field list from the rest of the query, so I am left with a string that may look like:

field1,field2,field3,CONCAT(field1,field2) AS concatted,IF(field1 = field2,field3,field4) AS logic

I think the logical approach would be to split the string on a comma, provided the comma doesn't appear within parantheses, so I just need to find the right regular expression to do that...?

The end result of what I'm trying to achieve is to find out which fields appear to be straight selects from the table, and which ones are made from SQL expressions, so that I can decide later whether to filter them using WHERE or HAVING clauses.

Once I have the list of fields, I can check for the presence of the 'AS' keyword which although isn't perfect, should work with the way I write SQL.

(Bonus points for suggesting another way that differenciates between fields that are not expressions but are aliased, and expressions that may not be aliased, or may be but without using 'AS')

  • 写回答

2条回答 默认 最新

  • douzhicui2209 2012-06-23 15:03
    关注

    This regex should work :

    /,(?![^()]*+\\))/
    

    An example implementation in PHP, here :

    $vv = 'field1,field2,field3,CONCAT(field1,field2) AS concatted,IF(field1 = field2,field3,field4) AS logic';
    
    $arr = preg_split ("/,(?![^()]*+\\))/", $vv);
    foreach ($arr as &$value) {
        print($value);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作