zoukankan      html  css  js  c++  java
  • php 批量替换html标签的实例代码

    php批量替换html标签的实例代码分享。
     
    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$tagstrue); // text
    ?>
  • 相关阅读:
    [UVa514] Rails
    今日才真正懂了BFS
    [UVa11292] Dragon of Loowater
    [UVa] TEX Quotes
    白书杂七杂八
    [OpenJudge] Feed_Accounting
    [OpenJudge] Jolly_Jumpers
    Restart
    Collection of Websites
    Oracle11完全卸载方法
  • 原文地址:https://www.cnblogs.com/linuxnotes/p/3474971.html
Copyright © 2011-2022 走看看