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实现XSS安全过滤的方法

本文实例讲述了php实现XSS安全过滤的方法。分享给大家供大家参考。具体如下: function remove_xss($val) { // remove all non-pri...

PHP内存使用情况如何获取

PHP内置函数memory_get_usage()能返回当前分配给PHP脚本的内存量,单位是字节(byte)。在WEB实际开发中,这些函数非常有用,我们可以使用它来调试PHP代码性能。...

PHP CURL post数据报错 failed creating formpost data

在做微信卡券使用curl上传logo图片时,发现一个报错: failed creating formpost data 代码中数组如下: $data = array('buffer...

处理单名多值表单的详解

就使用一个简单的可多选的select:复制代码 代码如下:<?phpecho<<<EOT<form action="" method=get>&nbs...

PHP快速排序quicksort实例详解

本文实例讲述了PHP快速排序quicksort。分享给大家供大家参考,具体如下: quicksort 在快速排序算法中,使用了分治策略。首先把序列分成两个子序列,递归地对子序列进行排序,...