从aioobe的代码开始,我尝试了更大胆的:
String input = "<font size=\"5\"><p>some text</p>\n<p>another text</p></font>";
String stripped = input.replaceAll("</?(font|p){1}.*?/?>", "");
System.out.println(stripped);
去除每个 HTML 标记的代码如下所示:
public class HtmlSanitizer {
private static String pattern;
private final static String [] tagsTab = {"!doctype","a","abbr","acronym","address","applet","area","article","aside","audio","b","base","basefont","bdi","bdo","bgsound","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dir","div","dl","dt","element","em","embed","fieldset","figcaption","figure","font","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","iframe","img","input","ins","isindex","kbd","keygen","label","legend","li","link","listing","main","map","mark","marquee","menu","menuitem","meta","meter","nav","nobr","noframes","noscript","object","ol","optgroup","option","output","p","param","plaintext","pre","progress","q","rp","rt","ruby","s","samp","script","section","select","shadow","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","title","tr","track","tt","u","ul","var","video","wbr","xmp"};
static {
StringBuffer tags = new StringBuffer();
for (int i=0;i<tagsTab.length;i++) {
tags.append(tagsTab[i].toLowerCase()).append('|').append(tagsTab[i].toUpperCase());
if (i<tagsTab.length-1) {
tags.append('|');
}
}
pattern = "</?("+tags.toString()+"){1}.*?/?>";
}
public static String sanitize(String input) {
return input.replaceAll(pattern, "");
}
public final static void main(String[] args) {
System.out.println(HtmlSanitizer.pattern);
System.out.println(HtmlSanitizer.sanitize("<font size=\"5\"><p>some text</p><br/> <p>another text</p></font>"));
}
}
我写这个是为了符合 Java 1.4,出于一些可悲的原因,所以请随意使用 StringBuilder...
优点:
- 您可以生成要去除的标签列表,这意味着您可以保留您想要的标签
- 避免剥离不是 HTML 标记的内容
- 保留空格
缺点:
- 您必须列出所有要从字符串中去除的 HTML 标记。这可能很多,例如,如果您想剥离所有内容。
如果您发现任何其他缺点,我真的很高兴知道它们。