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

yipeiwu_com5年前PHP代码库

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

strip_tags 函数

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

使用方法:

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

复制代码 代码如下:

$str = "<p>我来自<b><a href='//www.jb51.net'>【宜配屋www.yipeiwu.com】</a></b></p>";

1,不保留任何HTML标签,代码会是这样:

复制代码 代码如下:

echo strip_tags($str);
// 输出:我来自【宜配屋www.yipeiwu.com】

2,只保留<a>一个标签的话,只需要将<a>字符串写到strip_tags的第二个参数中:
 

复制代码 代码如下:

echo strip_tags($str, "<a>");
// 输出:我来自<a href='//www.jb51.net'>【宜配屋www.yipeiwu.com】</a>

3,要保留<p>与<b>…多个标签,只需要将多个标签用空格分隔后写到strip_tags的第二个参数中:
 

复制代码 代码如下:

echo strip_tags($str, "<p> <b>");
// 输出:<p>我来自<b>【宜配屋www.yipeiwu.com】</b></p>

如果要使用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'));

相关文章

php使用NumberFormatter格式化货币的方法

本文实例讲述了php使用NumberFormatter格式化货币的方法。分享给大家供大家参考。具体实现方法如下: $amount = '12345.67'; $formatter =...

thinkphp关于简单的权限判定方法

实例如下: <li> <label>权限</label> <cite> <input name="MB_right" type...

UCenter中的一个可逆加密函数authcode函数代码

复制代码 代码如下: function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) { $ckey_...

兼容性最强的PHP生成缩略图的函数代码(修改版)

复制代码 代码如下: function ImageResize($srcFile,$toW,$toH,$toFile="") { if($toFile==""){ $toFile = $...

php 中奖概率算法实现代码

实现代码: <?php /** *php 中奖概率算法 * */ function get_zj( $jp ,$glname = 'gl'){ $sum = 0...