php method to remove html comments: 1. Open the corresponding PHP code file; 2. Check the format of html comments; 3. Use "preg_replace("/<!--[^\!\[]*?(?<!\/\/)-->/","",$html); "Method to remove html comments.
The operating environment of this article: Windows 7 system, PHP version 7.1, Dell G3 computer.
How to remove html comments in php?
PHP filter html comments
Filter html comments:
The so-called filtering is nothing more than matching and replacing strings. Here we use The regular matching replacement function preg_replace(reg,replace,string);, PHPers all know that the key to this function lies in the accuracy of reg, so let’s give it a try:
First of all, you must know the html comments The format is like this: .
Start regular writing
$html = "<!--something-->something"; $html = preg_replace("/<!--.*-->/","",$html); echo $html;
The above code will output something, it seems to be successful, don’t worry, test a few more examples
$html = "<!--something-->something<!--something-->"; $html = preg_replace("/<!--.*-->/","",$html); echo $html;
This example tells us, like this Writing could not achieve the effect we expected, so the regex was optimized like this
preg_replace("/<!--.*?-->/","",$html);
Well, I am satisfied now, but there will be such code in html, this is browser compatible code, obviously it cannot be filtered, so our regular expression continues to be optimized and becomes like this
preg_replace("/<!--[^\!\[]*?-->/","",$html);
And then if there is< in the html script> code, we need to change our matching rules again, change it to this
preg_replace("/<!--[^\!\[]*?(?<!\/\/)-->/","",$html);
In this case, I basically I have removed the html comments that I need to remove!
Unexpected harvest: During the optimization process, no multi-line comments were considered, but the rule unexpectedly matched the multi-line comments normally. I don’t know if it is because the html is read from a file!
After testing, we have not found that the main text is filtered out. If you have any questions, please leave a message to correct us.
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to remove html comments in php. For more information, please follow other related articles on the PHP Chinese website!