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

yipeiwu_com5年前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 zip压缩包操作类完整实例

本文实例讲述了PHP zip压缩包操作类。分享给大家供大家参考,具体如下: <?php /** * Zip 文件包工具 * * @author wengxianh...

php5.2 Json不能正确处理中文、GB编码的解决方法

php5.2新增的json功能是非常受欢迎的,但是经过测试发现, json_encode对中文的处理是有问题的, 1.不能处理GB编码,所有的GB编码都会替换成空字符. 2.utf8编码...

PHP之十六个魔术方法详细介绍

PHP中把以两个下划线__开头的方法称为魔术方法(Magic methods),这些方法在PHP中充当了举足轻重的作用。 魔术方法包括: __construct(),类的构造函数...

PHP实现通过get方式识别用户发送邮件的方法

本文实例讲述了PHP实现通过get方式识别用户发送邮件的方法。分享给大家供大家参考。具体如下: send_email.php如下: <?php $conn=mysq...

PHP中preg_match函数正则匹配的字符串长度问题

项目中,用preg_match正则提取目标内容,死活有问题,代码测得死去活来。 后来怀疑PHP 的preg_match有字符串长度限制,果然,发现“pcre.backtrack_limi...