How to remove empty tags in rich text? (Redactor or Twig) What is the preferred method to remove an empty tag from the content of a rich text element?

Example result:

&lt;p&gt;
  Lorem&lt;a href="…"&gt;&lt;/a&gt; ipsum
&lt;/p&gt;


When editing text in the WYSIWYG editor (Redactor) the result can contain empty anchor tags. This is a problem when navigating the page with the tab key, for instance, because the user can not see the focus anymore.

How can I automatically remove those artefacts?
I ended up using this solution:

Filter empty tags in Craft/Twig template

{{ entry.houseDescription|replace('/&lt;[^\\/&gt;][^&gt;]*&gt;&lt;\\/[^&gt;]+&gt;/', '')|raw }}



The replace filter /&lt;[^\\/&gt;][^&gt;]*&gt;&lt;\\/[^&gt;]+&gt;/ searches for empty tags and removes them.
The raw filter stops Twig from escaping HTML tags.


Regular expression test (RegExr)