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从5.3.28升级到5.3.29时Nginx出现502错误

今天将PHP从5.3.28升级到5.3.29,发现网站打不开了,提示”502 bad gateway”,访问静态资源可以,但访问任何PHP文件都会502。 其实之前也发现这个问题,只是一...

PHP快速排序算法实现的原理及代码详解

PHP快速排序算法实现的原理及代码详解

算法原理 下列动图来自五分钟学算法,演示了快速排序算法的原理和步骤。 步骤: 从数组中选个基准值 将数组中大于基准值的放同一边、小于基准值的放另一边,基准值位于中间位置 递归的对分...

php数组索引与键值操作技巧实例分析

本文实例讲述了php数组索引与键值操作技巧。分享给大家供大家参考。具体如下: <?php $array = array("a", "b","c"); //定义数组...

用PHP代替JS玩转DOM的思路及示例代码

事情的起源比较简单,我需要把一个导航页的数据整理好写入数据库。一个比较直观的方法是对html文件进行分析,通用的方法是用php的正则表达式来匹配。但是这样做开发和维护都很困难,代码可读性...

PHP删除二维数组中相同元素及数组重复值的方法示例

本文实例讲述了PHP删除二维数组中相同元素及数组重复值的方法。分享给大家供大家参考,具体如下: function assoc_title($arr, $key) { $tmp_a...