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)…
(<([a-z][a-z0-9]*)\b[^>]*>(.*?)</\2>)\s+
I can use $1
inside |replace
to refer to the entire tag found by the outer parentheses…
elems|replace('/(<([a-z][a-z0-9]*)\\b[^>]*>(.*?)</\\2>)\s/', '$1>,')
…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('/(<([a-z][a-z0-9]*)\\b[^>]*>(.*?)</$2>)\s/', '$1>,')
elems|replace('/(<([a-z][a-z0-9]*)\\b[^>]*>(.*?)</\\$2>)\s/', '$1>,')
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?