Home    Articles

 

How to remmove HTML tags along with their contents in php

 

In many cases we needed a function like strip_tags but we want to remove the content between HTML tags too.

Here is a function that does that, i took this function from php.net, it was written by mariusz.tarnaski.

I think here it will be more like "in front of your eyes" :) 

function strip_tags_content($text, $tags = '', $invert = FALSE) 
{ 
  preg_match_all('/<(.+?)[\s]*\/?[\s]*>/si', trim($tags), $tags); 
  $tags = array_unique($tags[1]); 
  if(is_array($tags) AND count($tags) > 0) 
  { 
    if($invert == FALSE) 
    { 
      return preg_replace('@<(?!(?:'. implode('|', $tags) .')\b)(\w+)\b.*?>.*?</\1>@si', '', $text); 
   	} 
    else 
    { 
      return preg_replace('@<('. implode('|', $tags) .')\b.*?>.*?</\1>@si', '', $text); 
    } 
  } 
  elseif($invert == FALSE) 
  { 
    return preg_replace('@<(\w+)\b.*?>.*?</\1>@si', '', $text); 
  } 
  return $text; 
}

How to use it:

Usage example: 
$text = '<b>example</b> text with <div>tags</div>'; 

Result for strip_tags($text): 
example text with tags 

Result for strip_tags_content($text): 
text with 

Result for strip_tags_content($text, '<b>'): 
<b>example</b> text with 

Result for strip_tags_content($text, '<b>', TRUE); 
text with <div>tags</div> 

Enjoy!

by