Remove tag (strip_tags()) html along with content - PHP

Asked

Viewed 1,032 times

0

When I use the internal function strip_tags() to remove a tag html, it removes only the tag itself <p></p>. But I would like to see its contents removed as well <p>teste</p>. Any idea?

  • It is not better to use JavaScript?

  • In this specific case I need to use only PHP. It is only a maintenance in an existing class. @Shutupmagda

2 answers

2

You can use preg_replace

$yourString = 'Hello <div>Planet</div> Earth. This is some <span class="foo">sample</span> content! <p>Hello</p>';
$regex = '/<[^>]*>[^<]*<[^>]*>/';
echo preg_replace($regex, '', $yourString);

This will return:

Hello Earth. This is some content!

If you need to remove a specific tag, it can be done this way:

echo preg_replace('/<h1[^>]*>([\s\S]*?)<\/h1[^>]*>/', '', 'Hello<h1>including this content</h1> There !!');

This will return

Hello There

There is a topic in stackoverflow https://stackoverflow.com/questions/2630159/strip-tags-and-everything-in-between

1


<?php 
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; 
} 

$text = '<b>sample</b> text with <div>tags</div>'; 
strip_tags_content($text): 
// saída: text with 

source: http://php.net/manual/en/function.strip-tags.php#86964

Browser other questions tagged

You are not signed in. Login or sign up in order to post.