How to delete specified html tags in php

青灯夜游
Release: 2023-03-09 20:46:02
Original
3666 people have browsed it

php method to delete specified html tags: 1. Use strip_tags() function, syntax "strip_tags(string,allow)"; 2. Use strip_html_tags() function, syntax "strip_html_tags(tags,str)".

How to delete specified html tags in php

The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer

php delete the specified html Tag method

$str='<p><p>这里是p标签</p><img src="" alt="这里是img标签"><a href="">这里是a标签</a><br></p>';
Copy after login

1: Delete all or keep the specified html tags

The function strip_tags that comes with php can meet the requirements,

Usage:

strip_tags(string,allow)
Copy after login
  • string: the string that needs to be processed;

  • allow: the specified tag that needs to be retained, you can write Multiple;

echo strip_tags($str,&#39;<p><a>&#39;);//输出:<p>这里是p标签</p><a href="">这里是a标签</a>
Copy after login

The advantage of this function is that it is simple and crude;

But the shortcomings are also obvious;

If there are a lot of tags;

And I just want to delete the specified one;

That requires writing a lot of tags that need to be retained;

So there is a second method;

2: Delete the specified html tag

Usage:

strip_html_tags($tags,$str);
Copy after login
  • $tags: Tags that need to be deleted (array format)

  • $str: the string that needs to be processed;

function strip_html_tags($tags,$str){
    $html=array();
    foreach ($tags as $tag) {
        $html[]="/(<(?:\/".$tag."|".$tag.")[^>]*>)/i";
    }
    $data=preg_replace($html, &#39;&#39;, $str);
    return $data;
}
echo strip_html_tags(array(&#39;p&#39;,&#39;img&#39;),$str);
//输出:<div>这里是p标签<a href="">这里是a标签</a><br></div>;
Copy after login

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to delete specified html tags 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!