Search code examples
phpregextemplate-enginepreg-replace-callback

Regex conditition


I have a problem with my condition on my template class. What am i doing wrong?

/@if\((?P<condition>.*)\)\n*\s*(?P<content>(?s:[\=\"\;\,\$\{\}\_\(\)\.\!\'\-\:\s\/\<\>\w\näöüÄÖÜèéà@]*))@endif/m

REGEX Link : https://regex101.com/r/hE4hX3/3


Solution

  • Instead of using list of allowed characters, use the list of forbidden characters with negated character classes. Example:

    ~
    @if \( (?P<condition> [^)]* ) \)
    \s*
    (?P<content> [^@]*+ (?: @(?!endif\b) [^@]* )*+ )
    @endif
    ~x
    

    demo

    In place of .* for the condition (that doesn't know where to stop), use [^)]* that grabs all until the closing parenthesis.

    Same thing for the content, use [^@]* and check after each "@" if "endif" follows. (in this way "@" is allowed in the content.)

    Other things: writing \n*\s* doesn't make sense because the two are optional and \s already contains \n, that's why I removed it.