您好,欢迎访问一九零五行业门户网

php去除字符串中的HTML标签方法总结

php去除字符串中的html标签方法有很多的今天在做一个采集小功能时发现了有n种方法,下面我为各位整理一下有原创的也有整理的,希望对大家有帮助。
先来看自己的写法
 代码如下 复制代码
str_replace(
,'',str_replace('
','',str_replace('','',$vv)))
这个最简单就是替换$vv变量中指定的两个div了,后来发现有一个办法
 代码如下 复制代码
$info = strip_tags($vv);
发现替换了所有html标签了,一面来看看strip_tags函数
trip_tags(string,allow):函数剥去 html、xml 以及 php 的标签。
 代码如下 复制代码
$str = '郭碗瓢盆-php';
$str1 = strip_tags($str);          // 删除所有html标签
$str2 = strip_tags($str,''); // 保留 标签
echo $str1; // 输出 郭碗瓢盆-php
echo $str2; // 样式不一样喔
由上面可以知道,在php中只能保留一些html标签,而不能指定删除一些html标签,于是我自己动手写一个放我平时的lib库文件中了。
 代码如下 复制代码
/**
 * 移出指定的 html 标签
 */
function strip_only_tags($str, $tags, $stripcontent = false) {
  $content = '';
if (!is_array($tags)) {
    $tags = (strpos($str, '>') !== false ? explode('>', str_replace('    if (end($tags) == '') {
      array_pop($tags);
    }
  }
foreach($tags as $tag) {
    if ($stripcontent) {
      $content = '(.+|\s[^>]*>)|)';
    }
$str = preg_replace('#|\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标签。
其它类似信息

推荐信息