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实现异步数据调用的方法

浏览器和服务器之间只有一种面向无连接的HTTP协议进行通讯的,面向无连接的程序的特点是客户端请求服务端,服务端根据请求返回相应的程序,不能保持持久连接。这样就出现了一个问题,一个客户端的...

PHP获取当前文件的父目录方法汇总

方法一:先获得当前文件所在文件夹的长度,然后用substr来截取掉该长度: 复制代码 代码如下: $dirName = str_replace("\\", "/", dirna...

解析func_num_args与func_get_args函数的使用

func_num_args函数功能– 返回传递到函数的参数数目,其语法如下 : int func_num_args (void )。说明 : 返回传递到目前定义函数的参数数目。如果是从函...

php+resumablejs实现的分块上传 断点续传功能示例

本文实例讲述了php+resumablejs实现的分块上传 断点续传功能。分享给大家供大家参考,具体如下: resumablejs官网 http://www.resumablejs.co...

table标签的结构与合并单元格的实现方法

table标签的结构与合并单元格的实现方法

1.<table>标签的结构示例代码:复制代码 代码如下: <table border="1">      &l...