php batch replaces html tag instance code

  • 2020-11-25 07:10:54
  • OfStack

1. Remove all html elements, or keep some html tags


<?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>');
?>

The result is (with comments removed) :

< blockquote > Test paragraph. Other text
< p > Test paragraph. < /p > < a href="#fragment" > Other text < /a > < /blockquote > 2. Instead, remove only one html tag


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


Related articles: