Twig / PHP - Format string using Replace or Regex
Asked Answered
P

4

9

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

Pizor answered 17/4, 2015 at 16:35 Comment(4)
This should probably be handled in your business logic, not your template.Guesthouse
I agree but there isn't much logic to handle here, I am just playing around and learning.. I also would like to understand why regex is not workingPizor
because you need to add additional extension, look to my answer plsLocust
If you're using Symfony 4, there's a perfect doc here.Chemical
S
15

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

Scour answered 29/12, 2017 at 17:54 Comment(0)
M
4

This works for me just fine (Craft CMS):

{# Removes all characters other than numbers and + #}
{{ profile.phone|replace('/[^0-9+]/', '') }}
Myrilla answered 18/11, 2016 at 5:48 Comment(2)
That appears to be a Craft CMS-specific extension: craftcms.com/changelog#2-2-2579Sarilda
Yes, in Twig it just returns: The "replace" filter expects an array or "Traversable" as replace values, got "string".Ymir
L
3

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.

Locust answered 17/4, 2015 at 17:7 Comment(2)
So there isn't a built-in regex extension, either I have to extend Twig myself or use a third party filter?Pizor
as I know currenly Twig uses regexp only for comparisons twig.sensiolabs.org/doc/templates.html#comparisonsLocust
S
2

Anderson Ivan Witzke's answer is good, but outdated. Here is an update for 2023.

In the file where you set up your template environment, add this:

$twig->addFilter(
  new \Twig\TwigFilter('regexReplace', function ($string, $pattern, $replacement) {
  return preg_replace($pattern, $replacement, $string);
}));

Other than that, you can follow his answer: use it with {{myVar|preg_replace('/\\d+/','')}} (making sure to escape each backslash with an additional backslash).

Stavros answered 7/1, 2024 at 3:54 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.