Search code examples
phpregexpreg-replacepreg-replace-callback

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.

My RegEx-Code: \{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.

Is there a way to speed up my regular expression or do I have to accept that speed?


Solution

  • You may use

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

    See the regex demo

    Details

    • \{if\s - {if and a whitespace
    • (.+?) - Group 1: any one or more chars, as few as possible
    • } - a } char
    • \R - any line break sequence
    • ((?>(?!\{\/?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} - {/if} text