Heim  >  Artikel  >  Backend-Entwicklung  >  PHP strip_tags保留多个HTML标签的方法,strip_tags标签_PHP教程

PHP strip_tags保留多个HTML标签的方法,strip_tags标签_PHP教程

WBOY
WBOYOriginal
2016-07-12 08:50:38838Durchsuche

PHP strip_tags保留多个HTML标签的方法,strip_tags标签

本文介绍了PHP strip_tags函数保留多个HTML标签的方法,可以使用第二个参数来设置不需要删除的标签,主要涉及到strip_tags的第二个参数

strip_tags 函数

语法
string strip_tags ( string str [, string allowable_tags] )
返回一个去除了HTML标签的字符串;可以使用第二个参数来设置不需要删除的标签。

使用方法:

前提:假如现在有这样一个字符串,

复制代码 代码如下:
$str = "

我来自帮客之家

";

1,不保留任何HTML标签,代码会是这样:
复制代码 代码如下:
echo strip_tags($str);
// 输出:我来自帮客之家

2,只保留一个标签的话,只需要将字符串写到strip_tags的第二个参数中:
 
复制代码 代码如下:
echo strip_tags($str, "
");
// 输出:我来自
帮客之家

3,要保留

…多个标签,只需要将多个标签用空格分隔后写到strip_tags的第二个参数中:
 
复制代码 代码如下:
echo strip_tags($str, "

");
// 输出:

我来自帮客之家


如果要使用php删除html标记中的特定标签呢?

这个就需要代码来实现了,如下:

function strip_selected_tags($text, $tags = array()) {
  $args = func_get_args();
  $text = array_shift($args);
  $tags = func_num_args() > 2 ? array_diff($args, array($text)) : (array) $tags;
  foreach($tags as $tag) {
    if (preg_match_all('/<'.$tag.
        '[^>]*>([^<]*)</'.$tag.
        '>/iu', $text, $found)) {
      $text = str_replace($found[0], $found[1], $text);
    }
  }

  return preg_replace('/(<('.join('|', $tags).
    ')( | |.)*/>)/iu', '', $text);
}

$str = "[url="] 123[/url]";
    echo strip_selected_tags($str, array('b'));

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/1133109.htmlTechArticlePHP strip_tags保留多个HTML标签的方法,strip_tags标签 本文介绍了PHP 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