php 去掉指定的html标签及内容(转)

发布时间:2014-08-31 23:41:23 来源:http://www.yourcode.org 作者:Yourcode 点击:632次
本文章给家收集了大量的关于html标签的去除方法,很多朋友可能会想到使用strip_tags函数,但这个函数会把所有的html标签全部删除了,下面我来给大家介绍去掉指定的html标签及内容方法,有需

本文章给家收集了大量的关于html标签的去除方法,很多朋友可能会想到使用strip_tags函数,但这个函数会把所有的html标签全部删除了,下面我来给大家介绍去掉指定的html标签及内容方法,有需要了解的朋友可参考。

string strip_tags ( string str [, string allowable_tags] )

弊端 :

这个函数只能保留想要的html标签,就是参数string allowable_tags。

在yizero的评论中我知道了这个函数的参数allowable_tags的其他的用法。

1
2
strip_tags ( $source '' );  //去掉所以的html标签。
strip_tags ( $source '<div><img><em>' );  //保留字符串中的div、img、em标签。

如果想去掉的html的指定标签。那么这个函数就不能满足需求了。于是乎我用到了这个函数。

1
2
3
4
5
6
7
8
9
10
11
12
13
/**
* 删除指定的HTML标签及其中内容,暂时只支持单标签清理
*
* @param string $string -- 要处理的字符串
* @param string $tagname -- 要删除的标签名称
* @param boolean $clear -- 是否删除标签内容
* @return string -- 返回处理完的字符串
*/
function  replace_html_tag( $string $tagname $clear  = false){
     $re  $clear  ''  '1' ;
     $sc  '/<'  $tagname  '(?:s[^>]*)?>([sS]*?)?</'  $tagname  '>/i' ;
     return  preg_replace( $sc $re $string );
}

以下是测试代码

1
2
3
4
5
6
7
8
9
10
// 百度首页内容
$string  file_get_contents ( 'http://www.baidu.com/' );
// 去掉 style 及包含内容
$string  = replace_html_tag( $string 'style' , true);
$string  = replace_html_tag( $string 'script' , true);
// 去掉 a 标签,并保存其中内容
$string  = replace_html_tag( $string 'a' );
// 去掉 span 标签,并保存其中内容
$string  = replace_html_tag( $string 'span' );
echo  $string ;

如果我们要删除指定两者之间的数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?php
/**   
* PHP去掉特定的html标签 
* @param array $string   
* @param bool $str  
* @return string 
*/  
function  _strip_tags( $tagsArr , $str ) {   
     foreach  ( $tagsArr  as  $tag ) {  
         $p []= "/(<(?:/" . $tag . "|" . $tag . ")[^>]*>)/i" ;  
     }  
     $return_str  = preg_replace( $p , "" , $str );  
     return  $return_str ;  
}  
   
$str  "<b>您好</b><input type='text' name='' /><a href='http://www.baidu.com'>百度一下,你就知道</a>" ;  
echo  _strip_tags( array ( "b" "input" "a" ), $str ); #去掉 B 标签和 INPUT 标签  
?>

转载于:https://www.cnblogs.com/huojing/articles/4121239.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值