MDL-47712 filter_mathjax: Improve mathjax filter replacement

The basic replacement which happened before did not consider the validity
of the HTML markup. As a result, modern browsers removed the invalid markup
in some situations, which has a result of the mathjax loader not working
with the relevant content.