php去掉字符串中指定的html标签,我们不能使用strip_tags()函数,因为这个函数只能保留想要的html标签,如:

strip_tags($string); //去掉$string字符串中所以的html标签. http://www.manongjc.com/article/1213.html

strip_tags($string,\'<div><img><em>\'); //去掉除了<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) == \'\') { 
      // http://www.manongjc.com/article/1213.html
      array_pop($tags); 
    } 
  } 
 
  foreach($tags as $tag) { 
    if ($stripContent) { 
      $content = \'(.+<!--\'.$tag.\'(-->|s[^>]*>)|)\'; 
    } 
 
    $str = preg_replace(\'#<!--?\'.$tag.\'(-->|s[^>]*>)\'.$content.\'#is\', \'\', $str); 
  } 
 
  return $str; 
} 

参数介绍:

  1. $str是指需要过滤的字符串。
  2. $tags是指要移除的html标签。
  3. $stripContent表示是否移除标签内的内容,默认为False,即不删除标签内的内容。

 

使用实例:

<?php
$string=\'<div><a href=\"http://www.manongjc.com\">码农教程<em>斜体</em></a><strong>加粗</strong></div>\'; 
$target = strip_only_tags($string, array(\'a\',\'em\'));//移除$string字符串内的a、em、b标签。 
var_dump($target);
$target = strip_only_tags($string, array(\'em\'),true); //移除$string字符串内的a、em、b标签,并移除标签里面的内容
var_dump($target);
?>
收藏 打印