dongmu7335 2013-10-09 17:22
浏览 31
已采纳

可以使用单个正则表达式完成此操作

I have a series of strings in the form:

{ method_name { $key1 = 'quoted value' , $key2 = __('literal value'); }}

// Missing method_name and final semi-colon
// Still valid
{{ $key1 = 'quoted value' , $key2 = __('literal value') }}

// Optional key values
{ method_name { $key1 = , $key2 = __('literal value'); }}
{ method_name { $key1, $key2 = __('literal value'); }}

// Any number of values
{ method_name { $key1 = 'quoted value' , $keyN = 3.14; }}

Currently, I use a series of preg_split and trim. This is part of a custom template engine where method_name informs the parser which method to call and $key = value will be passed to the method as an array. These strings are embedded in a HTML template and that DOM structure may be repeated. Think of it as a table with each row/column having a different value. The keys are the column details (name,sortable etc.) and the method will fill in details of the cell.

The problem I'm having is speed.

Q1. How can I do this with a single expression?

Q2. Will I gain any speed?

Q3. Provided I cache the result, is readability preferred over a somewhat complicated regex?

Q4. Is there any way I can restructure the strings for a performance boost?

Ideally, I'd like to scan the string only once, convert it to PHP code, and do an eval each time it needs to be used.

  • 写回答

2条回答 默认 最新

  • douyakan8924 2013-10-09 20:15
    关注

    I would perhaps use a regex like this (I found some parts to simplify from the one in the comments):

    (?:\{ (?:(?<method>.+?)\s+\{)?|\G)[,\s]*(?<key>\$\w+)(?: = (?<value>[^,
    ;}]*))?
    

    The named capture groups are self explanatory, but here's a breakdown:

    (?:
        \{ 
        (?:
            (?<method>.+?)   # Captures everything until the next { for the method
            \s+\{       
        )?                   # All this optional
        |
        \G                   # Or \G anchor, which will allow successive match of multiple key/value pairs
    )
    [,\s]*                   # Any spaces and commas
    (?<key>\$\w+)            # Capture of key with format $\w+
    (?: = 
        (?<value>[^,
    ;}]*)  # Capture of value
    )?                       # All this optional
    

    regex101 demo

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题