2

any idea why this: %20AND%20foo%3A%22(.+?)%22 won't match this: %20AND%20foo%3A%22some random string of characters%22 in the Twig |replace filter?

If i do this:

{% set foo = '%20AND%20foo%3A%22some random string of characters%22' %}
{% set bar = '%20AND%20foo%3A%22(.+?)%22' %}
{{ foo |replace(bar, 'replaced') }}
{# OR THIS #}
{{ foo |replace((bar), 'replaced') }}

The result is foo. Nothing gets replaced. I'd expect the result to be the string "replaced". What am I doing wrong?

3

UPDATE: As of Craft v2.2, the replace filter now supports regex:

The replace filter now supports regular expressions, by setting the first argument to a string that begins and ends with forward slashes, e.g. '/foo/'.

So this should work by adding forward slashes.

{% set bar = '/%20AND%20foo%3A%22(.+?)%22/' %}

I think this is particular to Craft and not native to the Twig replace filter.


I don't think the Twig replace filter will allow for regex matches.

According to this post, Twig only uses regular expressions with Comparisons.

But there are third-party plugins which might work:

| improve this answer | |
  • Got it sorted with Low Regex. Thanks for the hint! I was somehow under the impression that the |replace filter can do this. – Florian Dec 19 '14 at 12:49
  • As pointed out by Low, Craft's replace filter does now support regex. – Katrin Apr 29 '15 at 12:16

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.