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简单日历实现方法

PHP简单日历实现方法

本文实例讲述了PHP简单日历实现方法。分享给大家供大家参考,具体如下: 运行效果截图如下: 具体代码如下: <?php /* * Created on 2016-7...

PHP关于IE下的iframe跨域导致session丢失问题解决方法

今天搞的一个登录页面,被别的网站用iframe嵌进去后,死活无法登录(只在IE中存在这种情况)。 很明显,session无法被保存。但是直接在地址栏打开那个登录页面,一切都正常啊。真是奇...

php批量删除超链接的实现方法

清除掉一段html文本内容中的超链接最常见的写法可以如下: 复制代码 代码如下:$str=preg_replace("/<a[^>]*href=[^>]*>|&l...

php猴子选大王问题解决方法

本文实例讲述了php猴子选大王问题解决方法。分享给大家供大家参考。具体分析如下: 问题描述: 一群猴子排成一圈,按1,2,...,n依次编号。然后从第1只开始数,数到第m只,把它踢出圈,...

解析在apache里面给php写虚拟目录的详细方法

步骤1.首先打开AppServ\Apache2.2\conf里面的httpd.conf文件。在里面找到:LoadModule rewrite_module modules/mod_rew...