PHP移除指定HTML标签的方法

PHP默认的函数有移除指定html标签,名称为strip_tags,在某些场合非常有用。

strip_tags

(PHP 3 >= 3.0.8, PHP 4, PHP 5)

strip_tags — Strip HTML and PHP tags from a string

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的指定标签。那么这个函数就不能满足需求了。于是乎我用到了这个函数。

移除多个指定的html标签

/**
* Removes specific  tags.
*/
functionstrip_only_tags($str, $tags, $stripContent= FALSE) {
 $content= '';
 if(!is_array($tags)) {
   $tags= (strpos($str, '>') !== false ? explode('>', str_replace('<', '', $tags)) : array($tags));
   if(end($tags) == '') {
     array_pop($tags);
   }
 }
 foreach($tagsas$tag) {
   if($stripContent) {
     $content= '(.+<!--'.$tag.'(-->|\s[^>]*>)|)';
   }
   $str= preg_replace('#<!--?'.$tag.'(-->|\s[^>]*>)'.$content.'#is', '', $str);
 }
 return$str;
}

参数说明

$str  — 是指需要过滤的一段字符串,比如div、p、em、img等html标签。
$tags — 是指想要移除指定的html标签,比如a、img、p等。
$stripContent = FALSE  — 移除标签内的内容,比如将整个链接删除等,默认为False,即不删除标签内的内容。

使用说明

$target = strip_only_tags($source, array(‘a’,'em’,'b’));

移除$source字符串内的a、em、b标签。

实例说明

1


2

3
4
5
6
7

$source='<div><a href="http://www.lixiphp.com"target="_blank"><img src="http://blog.lixiphp.com/logo.png"border="0"

alt="Welcome to lixiphp."/>This a example from<em>lixiphp</em></a><strong>!</strong></div>

';
$target= strip_only_tags($source, array('a','em'));
//target results
//<div><img src="http://blog.lixiphp.com/logo.png" border="0" alt="Welcome to lixiphp." />This a example from<strong>!</strong></div>

声明:本站遵循署名-非商业性使用-相同方式共享 3.0共享协议. 转载请注明转自LixiPHP
来源:lixiphp 作者:Snippets

免责声明:本文仅代表作者个人观点,与世界朋友网无关。其原创性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容、文字的真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。

[责任编辑:世界朋友]