Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twig / PHP - Format string using Replace or Regex

Tags:

regex

php

twig

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

like image 799
Awena Avatar asked Apr 17 '15 16:04

Awena


3 Answers

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

like image 53
Anderson Ivan Witzke Avatar answered Nov 01 '22 12:11

Anderson Ivan Witzke


This works for me just fine (Craft CMS):

{# Removes all characters other than numbers and + #}
{{ profile.phone|replace('/[^0-9+]/', '') }}
like image 39
medoingthings Avatar answered Nov 01 '22 12:11

medoingthings


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

like image 3
Evgeniy Kuzmin Avatar answered Nov 01 '22 12:11

Evgeniy Kuzmin