3

I am searching the whole day for a RegEx that matches just the inner {IF} - {ENDIF}-Statement in a nested condition code. Does anyone have an idea?

for example:

{IF bla}Text 1{ELSEIF ble}Text 2 {IF bli}Text 2.1{ELSE blo}Text 2.1{ENDIF} Main text end{/ENDIF}

I just want to get

{IF bli}Text 2.1{ELSE blo}Text 2.1{ENDIF}

i tried #\{IF .*\}.*\{ENDIF\}#is but this is not working as i only get the whole string.

And also important: The code can have several lines and line breaks!

the bla, ble, bli etc are dynamic and can differ

2
  • 1
    I dont think regexp is the way here (similiar to parsing XML/HTML). I would consider parsing text manualy (traversing text, when you hit { you check for keyword). This way you can build a tree yourself and then take any node you need. Commented Aug 27, 2017 at 22:19
  • thanks, after long searching and failing i used that solution. Commented Aug 29, 2017 at 11:00

2 Answers 2

1

Inner IF-ELSE:

{IF(?!.*{IF).*?}.*?{ENDIF}

  • (?!.*{IF) looks ahead from that position and asserts it won't match
  • The lazy quantifiers ? are an instruction to stop at the earliest match.

Demo

Sign up to request clarification or add additional context in comments.

Comments

0

This grabs your inner IF block:

/{IF(?:.*?(?={IF)(*SKIP)(*FAIL)|.*?){ENDIF}/

Demo (279 steps)

The pattern uses (*SKIP)(*FAIL) and "disqualifies" any IF blocks that contain an inner IF block. This way you only get the innermost IF block.

Code: (Demo)

$string='{IF bla}Text 1{ELSEIF ble}Text 2 {IF bli}Text 2.1{ELSE blo}Text 2.1{ENDIF} Main text end{/ENDIF}';
echo  preg_match('/{IF(?:.*?(?={IF)(*SKIP)(*FAIL)|.*?){ENDIF}/',$string,$match)?$match[0]:'fail';

Output:

{IF bli}Text 2.1{ELSE blo}Text 2.1{ENDIF}

Or faster/better with negative lookahead:

/{IF(?!.*{IF).*?{ENDIF}/

Demo (190 steps)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.