我有 ..tpl 文件,其中包含以下行:
{$error|replace:"pno":"personal number error"}
我需要修改它,以便替换多个值,类似于:
{$error|replace:"pno_error":"personal number error", "error_1":"1", "error_2":"2"}
我需要确保代码的格式正确。我如何实现这一目标?
最佳答案
像这样
{assign "find" array('pno', 'error_1', 'error_2')}
{assign "repl" array('personal number error', 1, 2)}
{assign "text" 'error_1 and pno and error_2 are friends'}
{$text|replace:$find:$repl}
顺便说一句:不'cha宁愿通过 Controller 来完成它并在tpl文件中使用最终值?
编辑
how to make it to replace the exact match only, for example if the $text is 'pno', then replace it, but if the $text is 'pnopno', then do nothing?
在这种情况下,您可以使用正则表达式,但是,在数组中这是不可能的(据我所知),您需要一步一步地执行,或者更确切地说,一个命令一个命令地执行。
关于替换pno
而不是pnopno
,您需要找出自己的正则表达式来满足您的需求。
{assign "text" 'error_1 and pno and error_2 are friends'}
{$text|regex_replace:"/(\s)(pno)(\s)/":"personal number error"|regex_replace:"/(error_1)/":"1"|regex_replace:"/(error_2)/":"2"}
关于replace - smarty 替换多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20385120/