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编程实现脚本异步执行的方法

本文实例讲述了PHP编程实现脚本异步执行的方法。分享给大家供大家参考,具体如下: php语言得用fsockopen()函数,实现脚本异步运行,代码如下 异步请求函数(用debug参数若为...

PHP框架性能测试报告

作为一个PHP开发者,而且是初创企业团队的技术开发者,选择开发框架是个很艰难的事情。 用ThinkPHP的话,招聘一个刚从培训机构出来的开发者就可以上手了,但是性能和后期代码解耦是个让人...

PHP+.htaccess实现全站静态HTML文件GZIP压缩传输(一)

apache的强大终于超出了我的想象,仅仅蜻蜓点水般触及了一点php皮毛,这点皮毛就在我原有的知识库基础上爆炸开来,好像PN结的“雪崩击穿”一样,让我想到了多种技术结合无限的应用前景。...

php include的妙用,实现路径加密

1、中转程序include.inc 复制代码 代码如下: <? include_once 'include/Base.php'; $path = ''; $url = isBase...

php数据库操作model类(使用__call方法)

本文实例讲述了php数据库操作model类。分享给大家供大家参考,具体如下: 该数据库操作类使用__call()方法实现了数据的查找功能。 代码如下: <?php /*...