我对创建自己的模板引擎的正则表达式有问题。 我的代码:自定义模板的正则表达式 - 嵌套(PHP)
$re_foreachelse = '%
{foreach (.+?) as (.+?)}
(
[^{]*
(?:
{
(?!/?foreach(.*?)})
[^{]*
)*
)
{foreachelse}
(
[^{]*
(?:
{
(?!/?foreach(.*?)})
[^{]*
)*
)
{/foreach}
%x';
$re_foreach = '%
{foreach (.+?) as (.+?)}
(
[^{]*
(?:
{
(?!/?foreach(.*?)})
[^{]*
)*
)
{/foreach}
%x';
while(preg_match($re_foreachelse, $this->tpl)) $this->tpl = preg_replace($re_foreachelse, '[foreach $1 as $2]$3[foreachelse]$4[/foreach]', $this->tpl);
while(preg_match($re_foreach, $this->tpl)) $this->tpl = preg_replace($re_foreach, '[foreach $1 as $2]$3[/foreach]', $this->tpl);
我将生成PHP代码,但用于测试它仅变化 “{}” 至 “[]”。我的问题是,这适用于大多数嵌套标签:
[foreach $items as $item] $item [foreach $item as $i] $i [foreachelse][/foreach] $item [foreachelse][/foreach]
{foreach $items as $item} [foreach $tests as $test] [foreach $test as $t] [/foreach] [/foreach] {foreachelse} {/foreach}
[foreach $othertests as $test] [foreach $item as $i] $i [foreachelse][/foreach] [/foreach]
但是,正如你所看到的,一个没有改变,仍然有“{}”。它看起来像foreachlse foreachlse foreachl foreach作品,但不是另一种方式。
我只是正则表达式的初学者,我真的不知道问题出在哪里。 非常感谢您提供任何好的建议。
P.S .:对不起,我的英语不好。
仅使用regexp做这种工作注定会失败,您应该使用词法分析器+解析器。我的建议:看看[Twig代码](https://github.com/twigphp/Twig)([lexer](https://github.com/twigphp/Twig/blob/master/lib/Twig/Lexer) .php),[parser](https://github.com/twigphp/Twig/blob/master/lib/Twig/Parser.php)) – mTorres 2014-11-22 11:41:38