Using a back reference inside a regex search string within replace filter I’m trying to insert a programmatically generated id attribute into child elements of parsedown processed text. I'm aware that Craft’s twig replace filter incorporates preg_replace, so…

I have a regex search string that finds an HTML tag and its contents. It includes an inner back reference to make sure that the closing tag matches the opening tag (as opposed to some nested closing tag)…

(&lt;([a-z][a-z0-9]*)\b[^&gt;]*&gt;(.*?)&lt;/\2&gt;)\s+

I can use $1 inside |replace to refer to the entire tag found by the outer parentheses…

elems|replace('/(&lt;([a-z][a-z0-9]*)\\b[^&gt;]*&gt;(.*?)&lt;/\\2&gt;)\s/', '$1&gt;,')

…and then work with the results, but the problem (I think) is the syntax for the back reference inside the search string itself.

I've tried the following without success…

elems|replace('/(&lt;([a-z][a-z0-9]*)\\b[^&gt;]*&gt;(.*?)&lt;/$2&gt;)\s/', '$1&gt;,')
elems|replace('/(&lt;([a-z][a-z0-9]*)\\b[^&gt;]*&gt;(.*?)&lt;/\\$2&gt;)\s/', '$1&gt;,')

Where am I going wrong? Is this even possible with preg_replace? Or is there a better way to go about injecting attributes into parsedown processed text?
Backreferences within the regex are normally defined as \1, \2, etc. In the |replace filter you need to escape all backslashes, so it’ll be \\1, \\2, etc.