php 批量替换html标签的实例代码

yipeiwu_com5年前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
?>

相关文章

PHP7数组的底层实现示例

PHP7数组的底层实现示例

PHP 数组具有的特性 PHP 的数组是一种非常强大灵活的数据类型,在讲它的底层实现之前,先看一下 PHP 的数组都具有哪些特性。 可以使用数字或字符串作为数组健值 $arr =...

PHP实现创建微信自定义菜单的方法示例

本文实例讲述了PHP实现创建微信自定义菜单的方法。分享给大家供大家参考,具体如下: 在使用通用接口前,你需要做以下两步工作: 1.拥有一个微信公众账号,并获取到appid和appsecr...

功能强大的php分页函数

分页是每一个程序需要去理解的东西,学习过的几门语言中我发现分页原理都是一样的,下面为php初学者分析一下php分页实现与最后面补充了一个超级强大的分页函数。 文章内容分页主要有两个办法:...

php 生成随机验证码图片代码

复制代码 代码如下:<?php /** 默认首页 **/ class DefaultController extends AppController { public functi...

PHP简单实现遍历目录下特定文件的方法小结

本文实例讲述了PHP简单实现遍历目录下特定文件的方法。分享给大家供大家参考,具体如下: 1. 使用glob方法 foreach (glob("modules/*.php") as $...