Home » Html » Strip all HTML tags, except allowed

Strip all HTML tags, except allowed

Posted by: admin November 29, 2017 Leave a comment

Questions:

I’ve seen a lot of expressions to remove a specific tag (or many specified tags), and one to remove all but one specific tag, but I haven’t found a way to remove all except many excluded (i.e. all except p, b, i, u, a, ul, ol, li) in PHP. I’m far from good with regex, so I’d need a hand. 🙂 Thanks!

Answers:

strip_tags() does exactly this.

Questions:
Answers:

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>');

Questions:
Answers:

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;