REGEX to get information inside a string

Asked

Viewed 247 times

0

I’m studying PHP OO and part of my study is building a Class that works on a template engine. I converted the file to a string with file_get_contents and now I want to take a part of this string to generate a LOOP.

{LOOP}
   <option value="%SEL-VL%">%SEL-TXT%</option>
{ENDLOOP}

My idea is to use preg_match to take the content that is inside {LOOP} and {ENDLOOP} and make the replacements of the variables by repeating the html block that was caught.

I need help to create the REGEX that I will use in preg_macth. Can someone give me this strength?

I accept ideas too... NOTE: I do not use a ready-made framework or template engine available on the internet, as this development is part of my study and practice of PHP OO.

Thank you all.

1 answer

1


From what I understand, your question qualifies as Lexer or interpreter.

However you have your interval well defined, although you don’t know exactly how you will treat it afterwards.

You can use Regex :

({LOOP})(.*?)({ENDLOOP})

Explanation

  • ({LOOP}) - Group {LOOP} - Identifies the start of the capture.
  • ({ENDLOOP}) - Group {ENDLOOP} - Identifies the end of the capture.
  • (.*?) - Content Group - As little as possible to have no problem with another loop.

Be in Regex101.

Problem

Because it is an interpreter you can end up having the next problem on using Regex.

Solution

The ideal would be to work with conversions recursive, going from the inside out, after having everything converted, only do the opposite to mount the string final.

  • For the well defined range, pose to use as well: (?<={LOOP}) s*(.*?)(?={ENDLOOP})

  • I had already thought about this problem and had the idea of a solution with differentiated markers... type {LOOP1} {LOOP2} and in the instance when executing the method I would inform which LOOP I want to operate by inserting it in REGEX. Later separated the stretch between the LOOP, I would convert would make the simple substitution of Key => Value by %% demarcations. I’m still very weak in REGEX... I don’t quite understand the Solution.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.