php 批量替换html标签的实例代码

yipeiwu_com6年前PHP代码库

1.把html元素全部去掉,或者保留某几个html标签

复制代码 代码如下:

<?php
$text = '<p>Test paragraph.</p><!-- Comment --> <a href="#fragment">Other text</a>';
echo strip_tags($text);
echo "/n";

// Allow <p> and <a>
echo strip_tags($text, '<p><a>');
?>


结果为(去掉了注释):

<blockquote>Test paragraph. Other text
<p>Test paragraph.</p> <a href="#fragment">Other text</a></blockquote>2.相反,只去掉某一个html标签

复制代码 代码如下:

<?php
function strip_only($str, $tags, $stripContent = false) {
    $content = '';
    if(!is_array($tags)) {
        $tags = (strpos($str, '>') !== false ? explode('>', str_replace('<', '', $tags)) : array($tags));
        if(end($tags) == '') array_pop($tags);
    }
    foreach($tags as $tag) {
        if ($stripContent)
             $content = '(.+</'.$tag.'[^>]*>|)';
         $str = preg_replace('#</?'.$tag.'[^>]*>'.$content.'#is', '', $str);
    }
    return $str;
}

$str = '<font color="red">red</font> text';
$tags = 'font';
$a = strip_only($str, $tags); // red text
$b = strip_only($str, $tags, true); // text
?>

相关文章

PHP实现的随机IP函数【国内IP段】

本文实例讲述了PHP实现的随机IP函数。分享给大家供大家参考,具体如下: function get_rand_ip(){ $arr_1 = array("218","218","...

thinkphp中U方法按路由规则生成url的方法

如下所示: //更改模块配置文件 'URL_ROUTER_ON' => true, 'URL_ROUTE_RULES'=>[]//编写路由优化 tp开启路由后,使...

PHP解决URL中文GBK乱码问题的两种方法

一般情况下对URL进行UrlEncode 处理 , urlencode(),urldecode(); 也可以通过iconv('utf-8', 'gb2312', $ret)对接收到的数据...

PHP之uniqid()函数用法

本文实例讲述了PHP中uniqid()函数的用法。分享给大家供大家参考。具体方法分析如下: uniqid() 函数基于以微秒计的当前时间,生成一个唯一的 ID。 注释:由于基于系统时间,...

php 记录进行累加并显示总时长为秒的结果

现在有一个mysql数据库的test表里有一个duration字段,里面有三条记录: 00:22:32 13:42:21 134:42:21 表示的是时长,但是,保存类型是文本。 现在要...