简体   繁体   中英

Twig / PHP - Format string using Replace or Regex

How can I format a string in Twig as follows:

For example: 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

Better late than never...

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);
}));

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

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

This works for me just fine (Craft CMS):

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

如果您愿意在模板中执行此操作,尽管作为控制器/服务会更好,您可以启用preg_replace过滤器并使用preg_replace('/\\d+/','')类的内容去除数字并使用大写另外过滤。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM