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
?>

相关文章

删除html标签得到纯文本可处理嵌套的标签

方法基本上来自THinkphp中的源码,但是被我修改了一下 复制代码 代码如下: <?php /* *@Description:删除HTML标签,得到纯文本。可以处理嵌套的标签 *...

WordPress中用于检索模版的相关PHP函数使用解析

locate_template() 用来检索存在的优先级最高的模板文件,还能直接加载模板文件。 locate_template() 函数检索时,如果有子主题则优先使用子主题的模板,没有再...

一些php技巧与注意事项分析

从浏览器上看,使用 header(location) 就跳转到另一个页面了,但事实上,php却仍然会执行后台的代码的,假如后面的代码有不安全逻辑的,那就直接无视开发者设定的条件,继续把后...

用PHP编写和读取XML的几种方式

一.使用DOM生成和读取XML文件 实例一: 复制代码 代码如下: <?php //Creates XML string and XML document using the DO...

php中str_pad()函数用法分析

本文实例讲述了php中str_pad()函数用法。分享给大家供大家参考,具体如下: str_pad() 函数把字符串填充为新的长度。 语法: str_pad(string,ength,p...