smarty replace multiple values

假如想象 提交于 2021-02-08 02:06:14

问题


I have ..tpl file with this line:

{$error|replace:"pno":"personal number error"}

I need to modify it so multiple values will be replaced, sort of:

{$error|replace:"pno_error":"personal number error", "error_1":"1", "error_2":"2"}

I need to make sure the code is correctly formed. How do I achieve this?


回答1:


Like so

{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}

btw: dont'cha rather do it through a controller and in tpl files use final values?

EDIT

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?

In that case, you can use regular expressions, however, it is not possible in an array (as far as I know) and you need to do it step by step, or rather a command after command.

Regarding of replacing pno and not pnopno, you need to figure out your own regular expression to suit your needs.

{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"}



回答2:


You can also use the short code:

{$text = "error_1 and pno and error_2 are friends"}
{$find = ['pno', 'error_1', 'error_2']}
{$repl = ['personal number error', 1, 2]}

{$text|replace:$find:$repl}


来源:https://stackoverflow.com/questions/20385120/smarty-replace-multiple-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!