How to strip HTML tags using a black list in PHP?

2019-03-05 06:22发布

问题:

PHP strip_tags use a whitelist for skip some tags that you don't want were get rid. Anybody knows some implementation but using a blacklist instead of a whitelist?

回答1:

A simple compound regex search would work (if this is still about your previous issue):

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


回答2:

Try this function posted by LWC on 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
?>