Strip all HTML tags, except allowed

70,759

Solution 1

strip_tags() does exactly this.

Solution 2

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 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;
Share:
70,759
Lazlo
Author by

Lazlo

Updated on October 17, 2020

Comments

  • Lazlo
    Lazlo over 3 years

    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!