Twig / PHP - 使用替换或正则表达式格式化字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29704849/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 00:32:04  来源:igfitidea点击:

Twig / PHP - Format string using Replace or Regex

phpregextwig

提问by Awena

How can I format a string in Twig as follows:

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

For example: img = 05myphoto-Car.jpg

例如: 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

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

Desired Output:

期望输出:

Myphoto Car

I have tried this so far, from the docs:

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

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

Outputs String

输出字符串

05myphoto Car

I also tried {{ replace({'range(0, 9)': ""}) }} // for numeric prefix - did not work

我也试过 {{ replace({'range(0, 9)': ""}) }} // for numeric prefix - did not work

回答by Anderson Ivan Witzke

Better late than never...

迟到总比不到好...

Just register it (for me was on index.php)

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

$app['twig']->addFilter('preg_replace', new Twig_Filter_Function(function ($subject, $pattern, $replacement) {
    return preg_replace($pattern, $replacement, $subject);
}));

Then on the view: {{myVar|preg_replace('/\\d+/','')}}

然后在视图上: {{myVar|preg_replace('/\\d+/','')}}

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

请注意,所有反斜杠都必须转义,否则,它们将被 Twig 删除...

回答by medoingthings

This works for me just fine (Craft CMS):

这对我来说很好(Craft CMS):

{# Removes all characters other than numbers and + #}
{{ profile.phone|replace('/[^0-9+]/', '') }}

回答by Evgeniy Kuzmin

If you are willing to do it in the template, though it would be better as a controller/service, you can enable the preg_replacefilterand strip numbers with something like preg_replace('/\d+/','')and use the capitalize filter in addition.

如果您愿意在模板中执行此操作,尽管作为控制器/服务会更好,但您可以preg_replacepreg_replace('/\d+/','')使用类似的内容启用过滤器和条带编号,并另外使用大写过滤器。