php 去除所有 HTML 标签,允许的除外
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6247035/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Strip all HTML tags, except allowed
提问by Lazlo
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!
我已经看到很多表达式来删除特定标签(或许多指定标签),还有一个删除除一个特定标签之外的所有标签,但我还没有找到一种方法来删除除许多排除之外的所有标签(即所有除外p, b, i, u, a, ul, ol, li
) PHP。我对正则表达式很不擅长,所以我需要帮助。:) 谢谢!
回答by Rufinus
strip_tags()
does exactly this.
strip_tags()
正是这样做的。
回答by NullPoiиteя
you can do this by usingstrip_tags
function
你可以通过使用strip_tags
函数来做到这一点
? strip_tags— Strip HTML and PHP tags from a string
? strip_tags— 从字符串中去除 HTML 和 PHP 标签
strip_tags($contant,'tag you want to allow');
like
喜欢
strip_tags($contant,'<code><p>');
回答by aleemb
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.
如果您需要一些灵活性,您可以使用基于正则表达式的解决方案并以此为基础。strip_tags
如上所述,仍应是首选方法。
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;