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?

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.

|improve this answer|||||
  • Thank you Marion! Completely forgot about the trim filter - perfect solution :) – Katrin Apr 29 '15 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 May 17 '15 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('/\\/$/', '') }}
|improve this answer|||||

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.