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转换超过2038年日期出错的问题解决

前言 最近在写一个项目接口。测试中发现服务器上测试正常的功能,在本地一直有问题。一步步的排查,最终锁定问题是由于函数strtotime返回了一个false值,导致数据插入数据库失败。 相...

学习php设计模式 php实现桥梁模式(bridge)

学习php设计模式 php实现桥梁模式(bridge)

一、桥梁模式结构图   二、桥梁模式中主要角色 抽象化(Abstraction)角色:定义抽象类的接口并保存一个对实现化对象的引用。 修正抽象化(Refined Abstra...

PHP冒泡排序算法代码详细解读

复制代码 代码如下: <?php $arr = array(345,4,17,6,52,16,58,69,32,8,234); $n = count($arr); for($i=1...

file_get_contents获取不到网页内容的解决方法

复制代码 代码如下: <?php $url = "http://jb51.net/index.html"; $ch = curl_init(); $timeout = 5...

php 文件夹删除、php清除缓存程序

复制代码 代码如下: <?php header('content-type:text/html;charset=utf-8'); function delFile($fpath)...