Strip all HTML tags, except allowed
Solution 1:
you can do this by usingstrip_tags
function
¶ strip_tags — Strip HTML and PHP tags from a string
strip_tags($contant,'tag you want to allow');
like
strip_tags($contant,'<code><p>');
Solution 2:
strip_tags()
does exactly this.
Solution 3:
If you need some flexibility, you can use a regex-based solution and build upon it. strip_tags
as outlined above should still be the preferred approach.
The following will strips only tags you specify (blacklist):
// tags separated by vertical bar
$strip_tags = "a|strong|em";
// target html
$html = '<em><b>ha<a href="" title="">d</a>f</em></b>';
// Regex is loose and works for closing/opening tags across multiple lines and
// is case-insensitive
$clean_html = preg_replace("#<\s*\/?(".$strip_tags.")\s*[^>]*?>#im", '', $html);
// prints "<b>hadf</b>";
echo $clean_html;