In this tutorial I will show you how to remove HTML tags from a string using PHP.
Remove all Tags
PHP’s inbuilt strip_tags
function lets you remove all HTML tags from string and also provides you ability to ignore certain tags.
Here is example code on how to use
$string = "<p>Awesome</p><b> Website</b><i> by Narayan</i>";
echo strip_tags($string, "<b><i>");
?>
Output is
Remove all Tags with inner Content
strip_tags
doesn’t remove the content inside the removed tag. Here is how to remove the content too
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;
}
$string = "<p>Awesome</p><b> Website</b><i> by Narayan</i>. Thanks for visiting";
echo strip_tags_content($string, "<b><i>");
?>
Output is
This custom function also let’s you ignore some tags.
Remove Certain Tags
Here is code example on how to remove only certain tags from a string
$string = "<p>Awesome</p><b> Website</b><i> by Narayan</i>. Thanks for visiting";
$tags = array("p", "i");
foreach($tags as $tag)
{
$string = preg_replace("/<\\/?" . $tag . "(.|\\s)*?>/", $replace_with, $string);
}
echo $string;
?>
Output is
Remove Certain Tags with Content
Here is code example on how to remove only certain tags from a string with tag content
$string = "<p>Awesome</p><b> Website</b><i> by Narayan</i>. Thanks for visiting";
$tags = array("p", "i");
echo preg_replace('#<(' . implode( '|', $tags) . ')(?:[^>]+)?>.*?</\1>#s', '', $string);
?>
Output is