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的curl实现get,post和cookie(实例介绍)

类似于dreamhost这类主机服务商,是显示fopen的使用 的。使用php的curl可以实现支持FTP、FTPS、HTTP HTPPS SCP SFTP TFTP TELNET DI...

PHP面向对象程序设计之命名空间与自动加载类详解

本文实例讲述了PHP面向对象程序设计之命名空间与自动加载类。分享给大家供大家参考,具体如下: 命名空间 避免类名重复,而产生错误。 <?php require_once...

解析file_get_contents模仿浏览器头(user_agent)获取数据

什么是user agentUser Agent中文名为用户代理,简称 UA,它是一个特殊字符串头,使得服务器能够识别客户使用的操作系统及版本、CPU 类型、浏览器及版本、浏览器渲染引擎、...

php操作access数据库的方法详解

本文实例讲述了php操作access数据库的方法。分享给大家供大家参考,具体如下: 在PHP网站开发中,PHP与Mysql是最好的组合,但是当你想将其他平台的网站移植到PHP平台时,必然...

php下获取http状态的实现代码

逐风整理了两种方式,大家可以自行参考/使用: 复制代码 代码如下:#方式一$ch = curl_init('//www.jb51.net');curl_setopt($ch, CURL...