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中的mb_detect_encoding函数使用方法

php中可以使用 mb_detect_encoding() 函数来判断字符串是什么编码的。 当在php中使用mb_detect_encoding函数进行编码识别时,很多人都碰到过识别编码...

php中使用url传递数组的方法

本文实例讲述了php中使用url传递数组的方法。分享给大家供大家参考。具体分析如下: 数组传递这么写: 复制代码 代码如下:echo"<a href=2.php?info=...

PHP采用get获取url汉字出现乱码的解决方法

本文实例讲述了PHP采用get获取url汉字出现乱码的解决方法。分享给大家供大家参考。具体方法如下: 一、问题: 本来打算这样使用 复制代码 代码如下:<a href="list....

thinkphp 一个页面使用2次分页的实现方法

可以说是毫无技术含量的办法:将Page.class.php复制重命名一个,如nPage.class.php.并在nPage.calss.php中将$this->varPage=C(...

PHP实现的常规正则验证helper公共类完整实例

本文实例讲述了PHP实现的常规正则验证helper公共类。分享给大家供大家参考,具体如下: 主要代码功能: 弥补平时项目对于验证功能这块的不严谨。具体细分的常规验证, 手机号/电话/小灵...