問題描述
正則表達式錯誤,嵌套標籤 (Regex error, nested tags)
我正在嘗試用 PHP 為我的 MVC 框架編寫一個簡單的模板引擎。我正在編寫一個方法來處理我的模板中的條件,使用一些特殊的標籤。
我寫了這段代碼:
<?php
$text = '{% if var = val %}
{%if var1 = var1 %}
{% endif %}
{% endif %}
{%if var = val1 %}
{%if var1 = var1 %}
{% endif %}
{% endif %}';
function check_condition($text)
{
/*
1 ‑ preg_match_all (get all conditions)
2 ‑ scroll all the conditions
2.1 ‑ check if the condition is still present in the primary source
2.2 ‑ resolve the condition and get the text to print
3 ‑ replace the text in the primary source
*/
//1
if(preg_match_all('/{% if (.*) %}(.*){% endif %}/s', $text, $conditions))
{
//2
foreach($conditions as $condition)
{
//2.1
if(preg_match('/'.$condition[0].'/', $text))
{
//2.2
preg_match('/{% if (.*) %}/U', $condition[0], $data);
//check for and/or
$data = str_ireplace('{% if ', '', $data);
$data = str_ireplace(' %}', '', $data[0]);
$data = explode(' = ', $data);
if($data[0] == $data[1])
{
//3
$text = str_ireplace($condition[0], 'some text'.$condition[0], $text);
} else {
//check for else
}
}
}
}
return $text;
}
echo check_condition($text);
text var 包含條件示例,功能不完整。
這個正則表達式:
if(preg_match_all('/{% if (.*) %}(.*){% endif %}/s', $text, $conditions))
應該得到整個條件塊,在這種情況下:
[0] => '{% if var = val %}
{%if var1 = var1 %}
{% endif %}
{% endif %}'
[1] => '{%if var1 = var1 %}
{% endif %}'
[2] => '{%if var = val1 %}
{%if var1 = var1 %}
{% endif %}
{% endif %}'
[3] => '{%if var1 = var1 %}
{% endif %}'
但是它返回包含整個代碼的單個塊(從第一個 {%if .. %} 到最後一個 {%endif%})
問題在於嵌套條件,我認為正則表達式可以'處理這個。有人有想法麼?我該如何解決這個問題?還有其他方法可以使用嗎?
參考解法
方法 1:
Well .*
matches all the symbols it can get its hands on. Try using the "lazy" version by substituting .*
with .*?
. It should match the minimum possible characters to pass to the next part of the regular expression.
But this still wouldn't give you what you want I guess. start1 start2 end2 end1
will match on start1‑end2
even though it shouldn't. There should be some more checks between the if
and endif
that would account for other pairs contained within.