douzhannao5357 2012-03-09 17:44
浏览 40
已采纳

用正则表达式或替代方法替换唯一的嵌套语句

From the countless questions posted I know it's not possible/advisable to use regex to replace nested statements.

I'm wondering if it makes any difference in a case where statements are unique:

[if @test]TEST[if @second]SECOND[/if][/if]

I've gotten it work when the end blocks are also unique, which I know is clumsy workaround:

[if @test]TEST[if @second]SECOND[/if @second][/if @test]
$pattern = '%\[if @'.$dynamic.'.*?\](.*?)\[/if @'.$dynamic.'\]%s'; //Works with above

Is it possible to use regex without the end block being unique? Are there alternatives to regex that would accomplish this?

I would like to parse something like: [if @test]TEST[if @second]SECOND[/if][/if] with arbitrary nesting levels. If regex is not practical, can anyone suggest viable alternative in PHP?

  • 写回答

1条回答 默认 最新

  • douchibu7040 2012-03-09 18:57
    关注

    In a proper solution you should tokenize the string in to its basic components such as tags, comments, text and whatever else you have there. This step can be done with regex, and produces a flat list of tokens. Next you go trough the tokens building a parse tree with all the structure and details needed. (Both steps can be combined and done in one pass as well.)

    That way everything is under your control and you don't need to reparse any part of the code.

    On the other hand it can be done with regex, but then you are more limited, and you need to reparse the nested parts of the code for every added depth.

    Since you asked for a regex, here is one to match such nested ifs:

    ~
    \[if\ @(\w++)]
    (
        (?>
            (?: (?!\[if\ @\w++]|\[/if]) . )++
            |
            (?R)
        )*+
    )
    \[/if]
    ~xs
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行