PHP: strip_tags -remove specific html tag and content from string

Function : strip_tag() is used to remove all the tags from a given string.

Usage : strip_tags($string);

Example :

$text = “Haii <script>alert(‘Script code’)</script> this is testing <img src=’#’ /> Script <iframe src=’#’ width=’100′>iframe code</iframe>”;

echo strip_tags($text);

//output : Haii alert(‘Script code’) this is testing  Script iframe code

To remove all tags with content

$striped_text =  preg_replace(‘@<(w+)b.*?>.*?</1>@si’, ”, $text);

echo strip_tag($striped_text);

//output : Haii  this is testing  Script

To remove selected tags

function strip_selected_tags($text, $tags = array())
{
foreach ($tags as $tag){
if(preg_match_all(‘/<‘.$tag.'[^>]*>(.*)</’.$tag.’>/iU’, $text, $found)){
$text = str_replace($found[0],$found[1],$text);
}
}

return $text;
}

$tags = array( ‘script’, ‘iframe’);

echo strip_selected_tags($text,$tags);

//output : Haii alert(‘Script code’) this is testing <img src=’#’ /> Script iframe code

To remove selected tags with content

function strip_selected_tags_content($text, $tags = array())
{
$text = preg_replace(‘@<(‘. implode(‘|’, $tags) .’)b.*?>.*?</1>@si’, ”, $text);
return $text;
}

echo strip_selected_tags_content($text,$tags);

//output : Haii  this is testing <img src=’#’ /> Script

One thought on “PHP: strip_tags -remove specific html tag and content from string

Leave a Reply

Your email address will not be published. Required fields are marked *