5

Just trying to use Craft's Twig replace filter to remove number prefixes from the beginning of User Groups names and I have had to double escape the character classes etc to get it to work. I tried this...

{{ group.name|replace('/^\d+\.\s/','') }}{% if not loop.last %}, {% endif %}

and it didn't work so for some reason I tried this...

{{ group.name|replace('/^\\d+\\.\\s/','') }}{% if not loop.last %}, {% endif %}

...and it worked. Is there a sensible explanation for this as Regular Expressions are like Voodoo?!

2
  • Meant to say the docs show only single backslashes hence the confusion...
    – Neal Hulme
    Commented Oct 21, 2014 at 19:23
  • Neal, I came across the same mystery using Twig's matches operator, which was also wrong in Sensiolabs' docs.
    – carlcs
    Commented Oct 22, 2014 at 7:38

1 Answer 1

5

Twig auto-escapes the \ character so by the time it makes it to the Craft replace filter PHP code, the regex string looks like /^d+.s/.

By double escaping it, you're forcing the correct regex to make it through /^\d+\.\s/.

4
  • Glad there is a sensible explanation... is this documented anywhere for future reference?
    – Neal Hulme
    Commented Oct 21, 2014 at 20:12
  • Is now! buildwithcraft.com/docs/templating/filters#replace
    – Brad Bell
    Commented Oct 21, 2014 at 20:29
  • Awesome, thanks Brad!
    – Neal Hulme
    Commented Oct 21, 2014 at 20:46
  • This is not a Craft-CMS related comment, but I want to say I could only use the matches operator in TWIG to validate a string against a regular expression when I used double-escaping in my regexp. Commented May 16, 2022 at 18:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.