[英]Twig / PHP - Format string using Replace or Regex
如何在 Twig 中格式化字符串,如下所示:
例如: img = 05myphoto-Car.jpg
我需要删除数字前缀和-
我主要用它来根据文件名输出图像的标题
期望输出:
Myphoto Car
到目前为止,我已经从文档中尝试过这个:
{{ img |replace({'.jpg': "", '-' : " "}) }}
输出字符串
05myphoto Car
我也试过{{ replace({'range(0, 9)': ""}) }} // for numeric prefix - did not work
迟到总比不到好...
只需注册它(对我来说是在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 删除...
这对我来说很好(Craft CMS):
{# Removes all characters other than numbers and + #}
{{ profile.phone|replace('/[^0-9+]/', '') }}
如果您愿意在模板中执行此操作,尽管作为控制器/服务会更好,您可以启用preg_replace
过滤器并使用preg_replace('/\\d+/','')
类的内容去除数字并使用大写另外过滤。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.