Heim  >  Artikel  >  Backend-Entwicklung  >  PHP移除指定HTML标签方法总结_PHP教程

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

WBOY
WBOYOriginal
2016-07-13 16:57:311105Durchsuche

在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, ‘

PHP移除指定HTML标签方法总结_PHP教程’); 保留字符串中的div、img、em标签。

如果想去掉的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标签。

$source='


 ';
 
$target = strip_only_tags($source, array('a','em'));
 
//target results
//
Welcome to lixiphp.This a example from!

其它办法

 代码如下 复制代码


//取出br标记
function strip($str)
{
$str=str_replace("
","",$str);
//$str=htmlspecialchars($str);
return strip_tags($str);
}
?>


一个自定义的函数

/

 代码如下 复制代码
**
 * 取出html标签
 *
 * @access public
 * @param string str
 * @return string
 *
 */
function deletehtml($str) {
    $str = trim($str); //清除字符串两边的空格
    $str = strip_tags($str,"

"); //利用php自带的函数清除html格式。保留P标签
    $str = preg_replace("/t/","",$str); //使用正则表达式匹配需要替换的内容,如:空格,换行,并将替换为空。
    $str = preg_replace("/rn/","",$str);
    $str = preg_replace("/r/","",$str);
    $str = preg_replace("/n/","",$str);
    $str = preg_replace("/ /","",$str);
    $str = preg_replace("/  /","",$str);  //匹配html中的空格
    return trim($str); //返回字符串
}
 

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/631529.htmlTechArticle在php中我们最常用的指定HTML标签可以直接使用strip_tags函数来替换了,利用它可以过滤所有的html标签哦,下面我来给大家介绍除了此函数之...
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn