In PHP, you can use the preg_replace() function with regular expressions to delete html comments. This function can perform a regular expression search and replacement; the specific syntax format is "preg_replace('##','',string)".
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
How to delete html comments in php
The first thing that is more basic is:
$a = '<!--ceshi-->ceshi'; $a = preg_replace('#<!--.*-->#' , '' , $a); var_dump($a);
The above code will output ceshi.
But if it is the following string, it cannot achieve the effect we want
$a = '<!--ceshi-->ceshi<!--ceshi-->'; $a = preg_replace('#<!--.*-->#' , '' , $a); var_dump($a);
So we changed the matching rules to the following format
preg_replace('#<!--.*?-->#' , '' , $a);
But in If there is code like <!--[if lt IE 9]>ceshi<![endif]-->
in html, it cannot be removed, so we need to improve the matching rules and change Into the following format
preg_replace('#<!--[^\!\[]*?-->#' , '' , $a);
and then if there is <script><!--ceshi//--></script>
code in the html, we need Let’s change our matching rules to the following format
preg_replace('#<!--[^\!\[]*?(?<!\/\/)-->#' , '' , $a);
In this case, I will basically remove the html comments that I need to remove!
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to delete html comments in php. For more information, please follow other related articles on the PHP Chinese website!