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...