How to get the content between two self-defined tags?
I'm trying to write a simple template system, and I have a problem. If I have a string like this:
{% for x in xx %}
some string 1
{% endfor %}
{% for y in yy %}
some string 2
{% endfor %}
How could I get the contents some string 1
and some string 2
. I try to match them with the regular expression, which looks for {% for .+ in .+ %}
and {% endfor %}
and get the contents between them, but in this case, what it got is:
some string 1
{% endfor %}
{开发者_Go百科% for y in yy %}
some string 2
What should I do?
UPDATE:
I think what I need is a regular expression which can do things like this:count = 0
while not the end:
if match("{% for .+ in .+ %}")
count += 1
else if match("{% endfor %}")
count -= 1
if count == 0
// get contents between the first {% for in %} and the last {% endfor %}
Can regular expression count?
PHP already makes an excellent templating system, why do you want to complicate it further by relying on what will become a VERY complicated RegEx if you want a decent templating system.
Chances are you're using .*
somewhere in your regex, which is greedy. Try using .*?
instead, which is non-greedy.
(Also, for any kind of tag nesting, you aren't going to want to use regex like that; instead you'll need to actually have some kind of stack involved.)
精彩评论