3

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
    Oct 21 '14 at 19:23
  • Neal, I came across the same mystery using Twig's matches operator, which was also wrong in Sensiolabs' docs.
    – carlcs
    Oct 22 '14 at 7:38
3

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

3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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