Home Backend Development PHP Tutorial 总结php删除html标签和标签内的内容的方法

总结php删除html标签和标签内的内容的方法

Jun 23, 2016 pm 01:35 PM

经常扒别人网站文章的坑们;我是指那种批量式采集的压根不看内容的,少不了都会用到删除html标签的函数;这里介绍3种不同用途上的方法;

$str='<div><p>这里是p标签</p><img src="/static/imghw/default1.png"  data-src="" alt="  class="lazy"   alt="这里是img标签"><a href="">这里是a标签</a><br></div>';
Copy after login

1:删除全部或者保留指定html标签

php自带的函数strip_tags即可满足要求,

使用方法:strip_tags(string,allow);

string:需要处理的字符串;

allow:需要保留的指定标签,可以写多个;

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

次函数的优点是简单粗暴,但是缺点也很明显;如果有一大堆标签;而我只是想删除指定的某一个;那要写很多需要保留的标签; 所以有了第二个方法;

2:删除指定的html标签

使用方法:strip_html_tags($tags,$str);

$tags:需要删除的标签(数组格式)

$str:需要处理的字符串;

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

3:删除标签和标签的内容

使用方法:strip_html_tags($tags,$str);

$tags:需要删除的标签(数组格式)

$str:需要处理的字符串;

  <?php    function strip_html_tags($tags,$str){         $html=array();        foreach ($tags as $tag) {            $html[]='/(<'.$tag.'.*?>[\s|\S]*?<\/'.$tag.'>)/';        }        $data=preg_replace($html,'',$str);    }     echo strip_html_tags(array('a','img'),$str);       ?>   //输出<div><p>这里是p标签</p><img src="/static/imghw/default1.png"  data-src="" alt="  class="lazy"   alt="这里是img标签"><br></div>;
Copy after login

很多网站文章里面会带上网站名和链接,比如白俊遥博客;这个函数就是专治这种; 别拿这个函数采集本站啊;不然保证不打死你;

4:终极函数,删除指定标签;删除或者保留标签内的内容;

使用方法:strip_html_tags($tags,$str,$content);

$tags:需要删除的标签(数组格式)

$str:需要处理的字符串;

$ontent:是否删除标签内的内容 0保留内容 1不保留内容

  <?php    /**     * 删除指定的标签和内容     * @param array $tags 需要删除的标签数组     * @param string $str 数据源     * @param string $content 是否删除标签内的内容 默认为0保留内容    1不保留内容     * @return string     */    function strip_html_tags($tags,$str,$content=0){        if($content){            $html=array();            foreach ($tags as $tag) {                $html[]='/(<'.$tag.'.*?>[\s|\S]*?<\/'.$tag.'>)/';            }            $data=preg_replace($html,'',$str);        }else{            $html=array();            foreach ($tags as $tag) {                $html[]="/(<(?:\/".$tag."|".$tag.")[^>]*>)/i";            }            $data=preg_replace($html, '', $str);        }        return $data;    }    echo strip_html_tags(array('a'),$str,1);   ?>   //输出<div><p>这里是p标签</p><img src="/static/imghw/default1.png"  data-src="" alt="  class="lazy"   alt="这里是img标签"><br></div>;
Copy after login


前面扯了那么多;其实最后这个函数才是干货;一口气搞定各种标签删除的疑难杂症不费劲;

别看下面这张截图了;无非带点颜色好看,我主要是拿来凑图当文章封面的;



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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Working with Flash Session Data in Laravel Working with Flash Session Data in Laravel Mar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

PHP Logging: Best Practices for PHP Log Analysis PHP Logging: Best Practices for PHP Log Analysis Mar 10, 2025 pm 02:32 PM

PHP logging is essential for monitoring and debugging web applications, as well as capturing critical events, errors, and runtime behavior. It provides valuable insights into system performance, helps identify issues, and supports faster troubleshoot

cURL in PHP: How to Use the PHP cURL Extension in REST APIs cURL in PHP: How to Use the PHP cURL Extension in REST APIs Mar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Simplified HTTP Response Mocking in Laravel Tests Simplified HTTP Response Mocking in Laravel Tests Mar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

12 Best PHP Chat Scripts on CodeCanyon 12 Best PHP Chat Scripts on CodeCanyon Mar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

Customizing/Extending Frameworks: How to add custom functionality. Customizing/Extending Frameworks: How to add custom functionality. Mar 28, 2025 pm 05:12 PM

The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.

See all articles