1

I am trying to change all rgb colours in a bit of text/content. I have the RegEx working here in php using preg_replace:

preg_replace("/#[a-zA-Z0-9]{6}|rgb\((?:\s*\d+\s*,){2}\s*[\d]+\)|rgba\((\s*\d+\s*,){3}[\d\.]+\)|hsl\(\s*\d+\s*(\s*\,\s*\d+\%){2}\)|hsla\(\s*\d+(\s*,\s*\d+\s*\%){2}\s*\,\s*[\d\.]+\)/", "*****", $input_lines);

https://www.phpliveregex.com/p/oc2

But cannot seem to get it working in craft template code am trying is like this:

{% set svg_image = '
#ffffff
#ffffffasdf
asdf#ffffff
rgba(170,221,255,0.59)
rgba(170,221,255,0.59)asdf
rgb(0, 0, 0)
rgb(33, 44,66)
rgb(0,0,0)asdf
rgba(170,221,255,0.59dsaf)
' %} 

{% set svg_image_output = svg_image|replace({ '/#[a-zA-Z0-9]{6}|rgb\\((?:\\s*\\d+\\s*,){2}\\s*[\\d]+\\)|rgba\\((\\s*\\d+\\s*,){3}[\\d\\.]+\\)|hsl\\(\\s*\\d+\\s*(\\s*\\,\\s*\\d+\\%){2}\\)|hsla\\(\\s*\\d+(\\s*,\\s*\\d+\\s*\\%){2}\\s*\\,\\s*[\\d\\.]+\\)/': '****' }) %}
{{ svg_image_output | raw }}

I have: - added double-escaped '\' as the docs suggest in v2 - started with / and ended with /

Seems in the docs that if this is done it works like preg_replace.

Any ideas?

2

You were close!

Just don't use the Twig hash/array syntax when using the |replace filter if you want Craft to process it as regex. This should do what you're looking for:

{% set svg_image_output = svg_image|replace('/#[a-zA-Z0-9]{6}|rgb\\((?:\\s*\\d+\\s*,){2}\\s*[\\d]+\\)|rgba\\((\\s*\\d+\\s*,){3}[\\d\\.]+\\)|hsl\\(\\s*\\d+\\s*(\\s*\\,\\s*\\d+\\%){2}\\)|hsla\\(\\s*\\d+(\\s*,\\s*\\d+\\s*\\%){2}\\s*\\,\\s*[\\d\\.]+\\)/', '****') %}

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.