Neonlight Neonlight - 6 months ago 11
PHP Question

Regex conditition

Good evening

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


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

Answer

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.