【问题标题】:How to strip HTML tags using a black list in PHP?如何在 PHP 中使用黑名单去除 HTML 标签?
【发布时间】:2011-02-14 20:37:33
【问题描述】:

PHP strip_tags 使用白名单来跳过一些你不想被删除的标签。任何人都知道一些实现,但使用黑名单而不是白名单?

【问题讨论】:

    标签: php parsing html-parsing strip-tags


    【解决方案1】:

    一个简单的复合正则表达式搜索就可以了(如果这仍然是关于您之前的问题):

    $html =
    preg_replace("#</?(font|strike|marquee|blink|del)[^>]*>#i", "", $html);
    

    【讨论】:

    • 请解释一下这部分:[^>]*
    • @texai: [^&gt;]* 是匹配 HTML 标签内所有内容的常用方法。它匹配任意数量的闭合&gt;尖括号的字符。正则表达式部分[^...] 表示negated character class
    【解决方案2】:

    试试 LWC 在 php.net 上发布的这个功能 - http://www.php.net/manual/en/function.strip-tags.php#96483

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-02-01
      • 1970-01-01
      • 2012-10-19
      • 1970-01-01
      • 2014-06-18
      • 2023-04-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多