开发者

Strip all HTML tags, except allowed

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!


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


strip_tags() does exactly this.


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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜