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反射机制来构造"CREATE TABLE"的sql语句

反射是指在PHP运行状态中,扩展分析PHP程序,导出或提取出关于类、方法、属性、参数等的详细信息,包括注释。这种动态获取的信息以及动态调用对象的方法的功能称为反射API。反射是操纵面向对...

PHP的explode和implode的使用说明

说到php,函数便长短常主要的,也是php爱好者,和喜好php进阶的朋友们必须控制的东东,学习php的友朋们也晓得,数组也是必需把握的,能够那样道,进阶php,也便是学习php中的数组而...

php正则匹配文章中的远程图片地址并下载图片至本地

使用php的正则表达式来实现: $content = '这里是文章内容,这里插入一张图片测试 <img src="XXXXXXXXXXXXXXXXXXXX">'; $c...

深入PHP curl参数的详解

curl_setopt (PHP 4 >= 4.0.2) curl_setopt -- 为CURL调用设置一个选项 描述 bool curl_setopt (int ch, str...

PHP会话操作之cookie用法分析

本文实例分析了PHP cookie用法。分享给大家供大家参考,具体如下: 会话技术:cookie 允许服务器端脚本在浏览器存储数据的技术, 允许服务器向浏览器发送指令,用来管理存储在浏...