今天在写项目中发现,发布一篇文章包含图片时数据库里存入的包含html标签,在文章列表中会显示这些标签,而不是过滤掉这些标签只展示内容,记录一下后台过滤的方法:
package com.util;
/**去除内容中html标签*/
public class HtmlSplit {
public static void main(String[] args) {
String html = "<p></p><p><font style=\"vertical-align: inherit;\"><font style=\"vertical-align: inherit;\">小号sssssssssssssssssssss</font></font></p>";
String htmlSplit = getHtmlSplit(html);
System.out.println(htmlSplit);
}
/**目前去除<a></a>,<img>,<p></p>,<br>,<div></div>,<iframe></iframe>,<span></span>,<h></h>,<font></font>标签,将其替换为空*/
public static String getHtmlSplit(String html){
html=html.replaceAll("<a href[^>]*>", "");
html=html.replaceAll("</a>", "");
html=html.replaceAll("<img[^>]*>", "");
html=html.replaceAll("<p[^>]*>", "");
html=html.replaceAll("</p>", "");
html=html.replaceAll("<br[^>]*>", "");
html=html.replaceAll("<div[^>]*>", "");
html=html.replaceAll("</div>", "");
html=html.replaceAll("<iframe src[^>]*>", "");
html=html.replaceAll("</iframe>", "");
html=html.replaceAll("<span style[^>]*>", "");
html=html.replaceAll("</span>", "");
html=html.replaceAll("<h1[^>]*>", "");
html=html.replaceAll("</h1>", "");
html=html.replaceAll("<h2[^>]*>", "");
html=html.replaceAll("</h2>", "");
html=html.replaceAll("<h3[^>]*>", "");
html=html.replaceAll("</h3>", "");
html=html.replaceAll("<h4[^>]*>", "");
html=html.replaceAll("</h4>", "");
html=html.replaceAll("<h5[^>]*>", "");
html=html.replaceAll("</h5>", "");
html=html.replaceAll("<font style[^>]*>", "");
html=html.replaceAll("</font>", "");
html=html.replaceAll(" ", "");
return html;
}
}
运行结果是:
上面是把html对应的标签进行替换了,也可以自行添加需要替换的标签
其实数据库可以再设置一个去除标签后的字段来保存这个内容,列表展示时只展示这个字段的内容,可以作为工具类使用:
这是通过后台进行正则表达式的过滤,也可以前台。