在 Java 中,我看到可以很容易地指定白名单标签并去除其余的 html 标签:
Whitelist whitelist = Whitelist.none();
whitelist.addTags(new String[] { "p", "br", "ul" });
String safe = Jsoup.clean(unsafe, whitelist);
return StringEscapeUtils.unescapeXml(safe);
PHP 还有 strip_tags($html, $whitelist)
函数来做同样的事情。
我在Android中看到,你可以这样做:
android.text.Html.fromHtml(instruction).toString()
但这会去除整个 html,包括 img 标签。
或者,Jsoup
库可以使用,但我们没有更简单的解决方案而不是使用这个 300kb
这个简单需求的库?
在 Android 中,我如何去除除 <img>
之外的所有 html给定文本中的标签 ?
最佳答案
这有点 hacky,但它完成了工作:
- 用一些特殊字符串替换所有 img 标签,这样剥离函数就看不到它们
- 去除所有 HTML
用特殊字符串替换 img 标签以取回它们。
String stripHTMLtagsExceptIMG(String htmlString) { String subbed = htmlString.replaceAll("< *[iI][mM][gG]", "_iimmgg"); String stripped = android.text.Html.fromHtml(subbed).toString(); String unsubbed = stripped.replaceAll("_iimmgg", "<img"); return unsubbed; }
关于Android:去除除 img 标签之外的所有 html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27739512/