【发布时间】:2013-12-10 09:31:34
【问题描述】:
我想匹配 smarty 模板中的 if else 语句。并在那里插入我自己的标签。在我的示例中,<OPEN> 和 </CLOSE>。
这是我的代码:
$value =
<<<SMARTY
{if}
text1
{if}
text2
{/if}
text3
{/if}
{if}
text1
{else}
text2
{/if}
{if}
text1
{if}
text2
{else}
text3
{/if}
text
{/if}
SMARTY;
echo filter($value);
function filter($value)
{
$pattern =
'(\{(?:if|else).*?\})'. // open
'((?:'.
'[^{]'.
'|\{(?!/?if|else)'.
'|(?R)'.
')+)'.
'(\{(?:\/if|else)\})'; // close
return preg_replace_callback('#'.$pattern.'#', 'filter_callback', $value);
}
function filter_callback($matches)
{
$m2 = $matches;
$m2[0] = preg_replace(array('/[\n\r]/','/ +/','/^ /'),array('',' ',''), $m2[0]);
$m2[2] = preg_replace(array('/[\n\r]/','/ +/','/^ /'),array('',' ',''), $m2[2]);
print_r($m2);
return $matches[1].'<OPEN>'.filter($matches[2]).'</CLOSE>'.$matches[3];
}
但它不能正常工作。
例如我想有以下输出:
{if}<OPEN>
text1
</CLOSE>{else}<OPEN>
text2
</CLOSE>{/if}
和
{if}<OPEN>
text1
{if}<OPEN>
text2
</CLOSE>{else}<OPEN>
text3
</CLOSE>{/if}
text
</CLOSE>{/if}
如果有人有想法?
【问题讨论】:
-
正则表达式本质上不是递归的,不能很好地处理递归匹配。为什么可以在这个答案中找到解释(HTML 也是一种递归语言,因此适用相同的原则):stackoverflow.com/a/1758162/334053 您只需为 Smarty 编写(或查找)一个解析器并做您想做的事情用 PHP 做。
-
@SpikeX 用于我在表达式中使用 (?R) (us2.php.net/manual/de/regexp.reference.recursive.php) 的递归
标签: php regex recursion smarty