我正在尝试编写一个简单的模板系统,但我遇到了问题。如果我有这样的字符串:
{% for x in xx %}
some string 1
{% endfor %}
{% for y in yy %}
some string 2
{% endfor %}
我如何获取内容some string 1
和some string 2
。我尝试将它们与正则表达式匹配,正则表达式查找{% for .+ in .+ %}
和{% endfor %}
并获取它们之间的内容,但在这种情况下,它得到的是:
some string 1
{% endfor %}
{% for y in yy %}
some string 2
我该怎么办?
更新
我认为我需要的是一个正则表达式,它可以做这样的事情:
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 %}
正则表达式可以计数吗?
答案 0 :(得分:2)
PHP已经成为一个出色的模板系统,如果你想要一个体面的模板系统,为什么还要依赖于什么将成为一个非常复杂的RegEx来进一步复杂化。
答案 1 :(得分:1)
你有可能在你的正则表达式的某个地方使用.*
,这是贪婪的。请尝试使用.*?
,而不是贪婪。
(另外,对于任何类型的标记嵌套,你都不会想要像这样使用正则表达式;相反,你需要实际涉及某种堆栈。)