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中heredoc的使用方法

Heredoc技术,在正规的PHP文档中和技术书籍中一般没有详细讲述,只是提到了这是一种Perl风格的字符串输出技术。但是现在的一些论坛程 序,和部分文章系统,都巧妙的使用heredoc...

PHP实现递归复制整个文件夹的类实例

本文实例讲述了PHP实现递归复制整个文件夹的类。分享给大家供大家参考。具体如下: <?php /* * 文件夹复制类 */ class CopyFile { pub...

两款万能的php分页类

本文为大家分享个超级好用、万能的php分页类,具体的实现代码如下 第一款php分页类 <?php /* * To change this template, choo...

php+html5基于websocket实现聊天室的方法

本文实例讲述了php+html5基于websocket实现聊天室的方法。分享给大家供大家参考。具体如下: html5的websocket 实现了双向通信,折腾了几天弄了个聊天室,分享给大...

php 不同编码下的字符串长度区分

UTF-8的中文字符串是三个字节 复制代码 代码如下: <?php //编码UTF-8 echo strlen('测试文字a测试文字'); echo '-'; echo mb_st...