Twig / PHP - 使用Replace或Regex格式化字符串
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Twig / PHP - 使用Replace或Regex格式化字符串相关的知识,希望对你有一定的参考价值。
如何在Twigg中格式化字符串:
例如img = 05myphoto-Car.jpg
我需要删除数字前缀和-
我主要使用它来根据文件名输出图像的标题
到目前为止我已尝试过这个(来自Docs)
{{ img |replace({'.jpg': "", '-' : " "}) }}
输出字符串
05myphoto Car
我也试过{{ replace({'range(0, 9)': ""}) }} // for numeric prefix - did not work
期望的输出
`Myphoto Car`
谢谢
答案
迟到总比不到好...
只需注册它(对我来说是在index.php
)
$app['twig']->addFilter('preg_replace', new Twig_Filter_Function(function ($subject, $pattern, $replacement) {
return preg_replace($pattern, $replacement, $subject);
}));
然后在视图上:{{myVar|preg_replace('/\d+/','')}}
请注意,所有反斜杠都必须进行转义,否则,它们将被Twig删除...
另一答案
如果你愿意在模板中这样做,虽然它会更好地作为控制器/服务,you can enable the preg_replace
filter和条带数字与preg_replace('/d+/','')
之类的东西并且另外使用大写过滤器。
另一答案
这对我很有用(Craft CMS):
{# Removes all characters other than numbers and + #}
{{ profile.phone|replace('/[^0-9+]/', '') }}
以上是关于Twig / PHP - 使用Replace或Regex格式化字符串的主要内容,如果未能解决你的问题,请参考以下文章