简体   繁体   English

可以加快 PHP 正则表达式

[英]it is possible to speed up PHP regex

I've tried to write a fast regular expression, but when I test it, PHP (preg_replace_callback) will have houndres of steps to get the results and I think that's not a good perfomance - that must be faster.我试图编写一个快速的正则表达式,但是当我测试它时,PHP (preg_replace_callback) 将有 houndres 的步骤来获得结果,我认为这不是一个好的性能 - 必须更快。

My RegEx-Code: \{if\s{1}(.+?)\}\n(((?R)|.*?)+)\{\/if\}我的正则表达式代码: \{if\s{1}(.+?)\}\n(((?R)|.*?)+)\{\/if\}

Code, that should be parsed (recursiveley):应该解析的代码(递归):

{if $name == 'Tree'}
    Hey, this is a Tree!
{/if}

{if $name == 'Example'}
    {if $number == '1'}
        Hey, this is an Example with the number 1
    {/if}
{/if}

You can test the example on regex101 here .您可以在此处测试 regex101 上的示例。

Is there a way to speed up my regular expression or do I have to accept that speed?有没有办法加快我的正则表达式或者我必须接受那个速度?

You may use您可以使用

(?s)\{if\s(.+?)}\R((?>(?!\{\/?if[}\s]).|(?R))*?)\{\/if}

See the regex demo查看正则表达式演示

Details细节

  • \{if\s - {if and a whitespace \{if\s - {if和一个空格
  • (.+?) - Group 1: any one or more chars, as few as possible (.+?) - 第 1 组:任何一个或多个字符,尽可能少
  • } - a } char } - 一个}字符
  • \R - any line break sequence \R - 任何换行符序列
  • ((?>(??\{\/.if[}\s])?|(?R))*?) - Group 2: any char other than a char starting a {/if or {if +whitespace char sequence, or the whole pattern recursed, 0 or more times, but as few as possible ((?>(??\{\/.if[}\s])?|(?R))*?) - 第 2 组:除以{/if{if +whitespace char 开头的字符外的任何字符序列,或整个模式递归,0次或多次,但尽可能少
  • \{\/if} - {/if} text \{\/if} - {/if}文本

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM