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

0

When I use the built-in strip_tags() function to remove a html tag, it removes only the tag itself <p></p> . But I'd like it to be removed as well. Any ideas?

    
asked by anonymous 16.01.2017 / 14:57

2 answers

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.*?>.*?</>@si', '', $text); 
    } else { 
      return preg_replace('@<('. implode('|', $tags) .')\b.*?>.*?</>@si', '', $text); 
    } 
  } elseif ($invert == FALSE) { 
    return preg_replace('@<(\w+)\b.*?>.*?</>@si', '', $text); 
  } 
  return $text; 
} 

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

source: link

    
16.01.2017 / 15:10
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 like this:

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 in English link

    
16.01.2017 / 15:05