background image

PHP 移除指定 HTML 标签方法总结

    在 php 中我们最常用的指定 HTML 标签可以直接使用 strip_tags 函数来替换了,利用它可
以过滤所有的

html 标签哦,下面我来给大家介绍除了此函数之外的其它办法。

php 中我们最常用的指定 HTML 标签可以直接使用 strip_tags 函数来替换了,利用它

可以过滤所有的

html 标签哦,下面我来给大家介绍除了此函数之外的其它办法。

有时候我们需要把

html 标签页存到

数据库

里,但是有些场合却需要拿无

html 标签的纯

数 据 , 这 个 时 候 就 要 对 带

html 标 签 的 数 据 进 行 处 理 , 把 html 标 签 都 去 掉 。 平 时 用

 

htmlspecialchars() 来过滤 html,但是把 html 的字符转义了,最后显示出来的就是 html 源代
码,利用

strip_tags()就可以把 html 标签去除掉。

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

strip_tags

strip_tags — Strip HTML and PHP tags from a string

string strip_tags ( string str [, string allowable_tags] )

弊端

 :

这个函数只能保留想要的

html 标签,就是参数 string allowable_tags。

这个函数的参数

allowable_tags 的其他的用法。

代码如下
strip_tags($source, ”); 去掉所以的 html 标签。

strip_tags($source, ‘<div><img><em>’); 保留字符串中的 div、img、em 标签。

如果想去掉的

html 的指定标签。那么这个函数就不能满足需求了。

于是乎我用到了这个函数。

代码如下
function strip_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($tags as $tag) {
    if ($stripContent) {
      $content = '(.+<!--'.$tag.'(-->|s[^>]*>)|)';
    }
 
    $str = preg_replace('#<!--?'.$tag.'(-->|s[^>]*>)'.$content.'#is', '', $str);
  }