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 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏