Twig/PHP - 使用替换或正则表达式格式化字符串 [英] Twig / PHP - Format string using Replace or Regex

查看:84
本文介绍了Twig/PHP - 使用替换或正则表达式格式化字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Twig 中格式化字符串,如下所示:

How can I format a string in Twig as follows:

例如:img = 05myphoto-Car.jpg

我需要删除数字前缀和-
我主要用它来根据文件名输出图像的标题

I need to remove the numeric prefix and -
I am mainly using this to output captions for images based on their filename

期望的输出:

Myphoto Car

到目前为止,我已经从文档中尝试过:

I have tried this so far, from the docs:

{{ img |replace({'.jpg': "", '-' : " "}) }}

输出字符串

05myphoto Car

我也试过 {{ replace({'range(0, 9)': ""}) }}//对于数字前缀 - 没有用

推荐答案

迟到总比不到好...

只需注册它(对我来说是在 index.php 上)

Just register it (for me was on 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 删除...

Notice that all backslashes MUST be escaped, if not, they will be removed by Twig...

这篇关于Twig/PHP - 使用替换或正则表达式格式化字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆