Filter HTML Comments:
The so-called filter, but the matching and substitution of strings, here we use the regular match replacement function preg_replace (reg,replace,string), phper know that the key to this function is the accuracy of Reg, then we will try it:
The first thing you need to know is the format of the HTML comment, which is:<!--comment.
Start the regular writing
$html = "<!--something-->something"; $html Preg_replace ("/<!--. *-->/", "",$html); Echo $html;
The above code will output something, it seems to be successful, no hurry, more tests a few examples
$html = "<!--something-->something<!--something-->"; $html Preg_replace ("/<!--. *-->/", "",$html); Echo $html;
This example tells us that this does not achieve the desired effect, so it is optimized to
Preg_replace ("/<!--. *?") -->/"," ",$html);
Well, that's satisfying, but there's a code like this in HTML <!--[if Lt IE 9]>something<! [Endif]-->, this is a browser-compatible code, obviously it cannot be filtered, so our regular continues to optimize, to become such
Preg_replace ("/<!--[^\!\[]*?-->/", "",$html);
And then if there's a <script><!--something//--></script> code in the HTML, we need to change our matching rules and change it.
Preg_replace ("/<!--[^\!\[]*?" (? <!\/\/)-->/"," ",$html);
In this case, I basically removed the HTML comments I need to remove!
Unexpected harvest: In the optimization process, there is no more comments to consider, but the rule unexpectedly correctly matched a multiline comment, do not know whether because it is read from the file html!
After testing has not found that the body filter out the situation, if in doubt, welcome to leave a message.
PHP Filter HTML comments