php 去掉指定的html标签及内容
本文章给家收集了大量的关于html标签的去除方法,很多朋友可能会想到使用strip_tags函数,但这个函数会把所有的html标签全部删除了,下面我来给大家介绍去掉指定的html标签及内容方法,有需要了解的朋友可参考。
string strip_tags ( string str [, string allowable_tags] )
弊端:这个函数只能保留想要的html标签,就是参数string allowable_tags,在yizero的评论中我知道了这个函数的参数allowable_tags的其他的用法,代码如下:
strip_tags($source, ]); 去掉所以的html标签。
strip_tags($source, ‘<div><img><em>’); 保留字符串中的div、img、em标签,如果想去掉的html的指定标签,那么这个函数就不能满足需求了,于是乎我用到了这个函数,代码如下:
<?php /** * 删除指定的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 ); }以下是测试代码,代码如下:
// php粉丝网首页内容 $string = file_get_contents ( 'http://HdhCmsTestphpfensi测试数据/' ); // 去掉 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 ; ?>如果我们要删除指定两者之间的数据,代码如下:
<?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://HdhCmsTestphpfensi测试数据'>php粉丝网</a>" ; echo _strip_tags( array ( "b" , "input" , "a" ), $str ); #去掉 B 标签和 INPUT 标签 ?>查看更多关于php 去掉指定的html标签及内容 - php函数的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://haodehen.cn/did30675