PHP Filter HTML comments

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.