4

I am trying to remove the http:// and trailing slash from a string, so my replace filter looks like this:

website|replace({ 'http://': '', '/\\/$/': '' })

The http:// part works, the trailing slash one doesn't. Why not?

2 Answers 2

7

I think you are getting the twig replace filter (which does not have the regex capability) instead of the Craft replace filter (which does).

So this is a bug in Craft, in that their filter is masked by the twig one.

You could use the trim filter to remove trailing /s:

website|replace({'http://':''})|trim('/')

Or you could use one of Victor's Twig PCRE Filters.

2
  • Thank you Marion! Completely forgot about the trim filter - perfect solution :)
    – Katrin
    Commented Apr 29, 2015 at 15:20
  • 1
    Craft's replace filter overrides Twig's, not visa-versa - although we do keep their base behavior in tact in ours. I've added an answer for the behavior you were seeing.
    – Brad Bell
    Commented May 17, 2015 at 19:49
2

Craft's replace filter only supports doing multiple strings replacements at once. If you want to do a regex replacement, it will have to be it's own separate call.

In your case, you'd have to do something like this:

{% set url =  "http://www.google.com/"|replace('http://', '') %}
{{ url|replace('/\\/$/', '') }}

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.