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使用HTML5 FileApi实现Ajax上传文件功能示例

PHP使用HTML5 FileApi实现Ajax上传文件功能示例

本文实例讲述了PHP使用HTML5 FileApi实现Ajax上传文件功能。分享给大家供大家参考,具体如下: FileApi是HTML5的一个新特性,有了这个新特性,js就可以读取本地的...

PHP基于自定义类随机生成姓名的方法示例

本文实例讲述了PHP基于自定义类随机生成姓名的方法。分享给大家供大家参考,具体如下: 自定义类rndChinaName.class.php: <?php Class r...

php通过array_unshift函数添加多个变量到数组前端的方法

本文实例讲述了php通过array_unshift函数添加多个变量到数组前端的方法。分享给大家供大家参考。具体分析如下: php通过array_unshift函数添加多个变量到数组前端,...

关于file_get_contents返回为空或函数不可用的解决方案

如果你使用file_get_contents获取远程文件内容返回为空或提示该函数不可用,也许本文能帮到你! 使用file_get_contents和fopen必须空间开启allow_ur...

php 错误处理经验分享

本教程介绍了 PHP 中一些最为重要的错误检测方法。 我们将为您讲解不同的错误处理方法: 简单的 "die()" 语句 自定义错误和错误触发器 错误报告 基本的错误处理:使用 die()...