I'm attempting to capture 4 attributes of an Attributes of an tag and injecting inline styles to the style attribute. Craft CMS and Twig templates are being used to generate HTML emails here, hence the inline styling.

This is my expression working in isolation: https://regexr.com/64a3f

And here is my twig replace:

{% set styledText = styledText
  |replace('/<a(?>\s+(?:href="([^"]*)"|class="([^"]*)"|target="([^"]*)"|style="([^"]*)")|[^\s>]+|\s+)*>/m', '<a href="$1" class="$2" style="' ~ linkColor ~ textDecoration ~ '$4" target="$3">')

The above is spitting out: <a href="" class="" style="color:#0000ff;text-decoration:underline;" target="">

So it appears all my capture groups are empty. The attribute values are not being carried over in the replace and I can't figure out why.

I have some simpler regular expressions working in Twig that just deal with class and style attributes.

I'm using Craft 3.5.x so the issue shouldn't be needing double backslashes. In fact, trying causes an internal server error.

If anyone has any thoughts that could help me get to the bottom of this I would greatly appreciate it.


  • That's a classic. You start out with one problem, try to solve it with regex – now you have two problems :) Since all you're doing is adding some inline styles, why not just use CSS? Or allow the editor of the styled text to add the styling themselves, somehow?
    – MoritzLost
    Aug 24, 2021 at 8:14

1 Answer 1


You could try to use Retcon for that:


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.