Home > Backend Development > PHP Problem > How to delete html comments in php

How to delete html comments in php

青灯夜游
Release: 2023-03-10 10:08:01
Original
2194 people have browsed it

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)".

How to delete html comments in php

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 = &#39;<!--ceshi-->ceshi&#39;;
    $a = preg_replace(&#39;#<!--.*-->#&#39; , &#39;&#39; , $a);
    var_dump($a);
Copy after login

The above code will output ceshi.

But if it is the following string, it cannot achieve the effect we want

    $a = &#39;<!--ceshi-->ceshi<!--ceshi-->&#39;;
    $a = preg_replace(&#39;#<!--.*-->#&#39; , &#39;&#39; , $a);
    var_dump($a);
Copy after login

So we changed the matching rules to the following format

preg_replace(&#39;#<!--.*?-->#&#39; , &#39;&#39; , $a);
Copy after login

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(&#39;#<!--[^\!\[]*?-->#&#39; , &#39;&#39; , $a);
Copy after login

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(&#39;#<!--[^\!\[]*?(?<!\/\/)-->#&#39; , &#39;&#39; , $a);
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template