dqkkrt8860 2008-12-23 20:39
浏览 40
已采纳

模板ifs使用正则表达式

Hey everyone, I'm working on a PHP application that needs to parse a .tpl file with HTML in it and I'm making it so that the HTML can have variables and basic if statements in it. An if statement look something like this: `

<!--if({VERSION} == 2)-->
Hello World
<!--endif -->

To parse that, I've tried using preg_replace with no luck. The pattern that I tried was

/<!--if\(([^\]*)\)-->([^<]*)<!--endif-->/e

which gets replaced with

if($1) { echo "$2"; }

Any ideas as to why this won't work and what I can do to get it up and running?

  • 写回答

3条回答 默认 最新

  • dongqia0240 2008-12-23 22:31
    关注

    I think you meant to do this:

    '/<!--if\(([^)]*)\)-->([^<]*)<!--endif-->/'
    

    Your regex has only one character class in it:

    [^\]*)\)-->([^<]
    

    Here's what's happening:

    • The first closing square bracket is escaped by the backslash, so it's matched literally.
    • The parentheses that were supposed close the first capturing group and open the second one are also taken literally; it isn't necessary to escape parens inside a character class.
    • The first hyphen is taken as a metacharacter; it forms the range [)*+,-]
    • The second opening square bracket is taken as a literal square bracket because it's inside a character class.
    • The second caret is taken as a literal caret because it's not the first character in the class.

    So, after removing the duplicates and sorting the characters into their ASCII order, your character class is equivalent to this:

    [^()*+,\-<>\[\]^]
    

    And the parentheses outside the character class are still balanced, so the regex compiles, but it doesn't even come close to matching what you wanted it to.

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

报告相同问题?

悬赏问题

  • ¥50 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?