duan89197 2016-04-21 15:20
浏览 47
已采纳

正则表达式在php中捕获函数参数

Currently I am trying to get all function parameters with regex for templating. The function parameters will be much like PHP compitable.

So here is the sample text needed to be parsed:

"test", 'test2', $test3, ?"%A %d %B %Y", "foo,bar,foobar"

This needed to be parsed to:

[
    '"test"',
    '\'test2\'',
    '$test3',
    '?"%A %d %B %Y"',
    '"foo,bar,foobar"'
]

I found this pattern but. When it has commas (,) in between double quotes it splits them too.

'~([^,]+\(.+?\))|([^,]+)~x'

The result of this pattern is:

[
    '"test"',
    ' \'test2\'',
    ' $test3',
    ' ?"%A %d %B %Y"',
    ' "foo,',
    'bar,',
    'foobar"'
]

I am not very good with regex patterns. I can achieve basic things with it but I couldn't find a way to achieve this.

  • 写回答

1条回答 默认 最新

  • duanquan1207 2016-04-21 15:30
    关注

    Your regex does not handle many things, and one of them is the double quoted value after a space. As the beginning has no optional whitespace pattern, the last alternative triggers, and stops at a comma.

    You can use the following regex:

    \s*("[^"\\]*(?:\\.[^\\"]*)*"|'[^'\\]*(?:\\.[^\\']*)*'|[^,]+),?
    

    See the regex demo, and grab Capture Group 1 values.

    Here is an IDEONE demo:

    $re = '~\s*("[^"\\\\]*(?:\\\\.[^\\\\"]*)*"|\'[^\'\\\\]*(?:\\\\.[^\\\\\']*)*\'|[^,]+),?~'; 
    $str = "\"test\", 'test2', \$test3, ?\"%A %d %B %Y\", \"foo,bar,foobar\""; 
    preg_match_all($re, $str, $tokens);
    print_r($tokens[1]);
    

    Pattern explanation:

    • \s* - zero or more whitespaces
    • ("[^"\\]*(?:\\.[^\\"]*)*"|'[^'\\]*(?:\\.[^\\']*)*'|[^,]+) - either of the 3 alternatives:
      • "[^"\\]*(?:\\.[^\\"]*)*" - double quoted strings (supporting escaped sequences)
      • | - or
      • '[^'\\]*(?:\\.[^\\']*)*' - single quoted strings (supporting escaped sequences)
      • | - or
      • [^,]+ - 1+ characters other than a comma
    • ,? - an optional comma (? - one or zero occurrences)
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)