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中substr()与explode()函数用法分析

本文实例讲述了PHP中substr()与explode()函数用法。分享给大家供大家参考。具体方法如下: substr(string,start,length):本函数将字符串 stri...

比较简单实用的PHP无限分类源码分享(思路不错)

下面一段代码是创建相应数据库的sql代码:复制代码 代码如下: //////////////   //////无限分类的数据库设计及样例 &nbs...

php扩展开发入门demo示例

本文实例讲述了php扩展开发。分享给大家供大家参考,具体如下: 一、进入php源码包,找到ext文件夹 cd /owndata/software/php-5.4.13/ext...

php类的自动加载操作实例详解

本文实例讲述了php类的自动加载操作。分享给大家供大家参考,具体如下: 类的自动加载 在外面的页面中,并不需要去引入类文件,但程序会在需要一个类的时候自动去“动态加载”该类。 ① 创建一...

PHP 用数组降低程序的时间复杂度

PHP 用数组降低程序的时间复杂度

而随着设备硬件配置的不断提升,对中小型应用程序来说,对算法的空间复杂度的要求也宽松了不少。不过,在当今 Web2.0 时代,对应用程序的时间复杂度却有了更高的要求。 什么是算法的时间复杂...