I am trying to parse some HTML snippets and want to clean them up for various reasons (XSS et al).
I am currently trying to remove all of the attributes on any tag, except for the href on a anchor. I am doing this using a sequence of eregi_replace calls, but I am sure there is a smarter way of doing this using preg_replace and just a couple of lines of code, but I have not been able to get it to work. Can anyone help?
Current code:
$data_item = eregi_replace("<p[^>]*>","<p>", $data_item);
$data_item = eregi_replace("<h2[^>]*>","<h2>", $data_item);
$data_item = eregi_replace("<h3[^>]*>","<h3>", $data_item);
$data_item = eregi_replace("<h4[^>]*>","<h4>", $data_item);
$data_item = eregi_replace("<h5[^>]*>","<h5>", $data_item);
$data_item = eregi_replace("<h6[^>]*>","<h6>", $data_item);
$data_item = eregi_replace("<ul[^>]*>","<ul>", $data_item);
$data_item = eregi_replace("<ol[^>]*>","<ol>", $data_item);
$data_item = eregi_replace("<li[^>]*>","<li>", $data_item);
$data_item = preg_replace("/<a([^>]*)( href=\S+)([^>]*)>/i", '<a$2 rel="nofollow">', $data_item);
(I only need to parse a subset of HTML tags as prior to this I strip out any undesireables).