方法一:
/**过滤HTML里去除img、p、span外的所有标签
* @param str
* @return
* @throws PatternSyntaxException
*/
public static String stringFilter(String str)throws PatternSyntaxException {
String regEx = "(?!<(img|p|span).*?>)<.*?>";
Pattern p_html = Pattern.compile(regEx, Pattern.CASE_INSENSITIVE);
Matcher m_html = p_html.matcher(str);
str = m_html.replaceAll("");
return str.trim(); // 返回文本字符串
}
方法二(会缺少一个jar包,请自行百度下载):
import org.apache.oro.text.perl.*;
class CleanHtml {
public static String clean(String html){
StringBuffer buffer = new StringBuffer();
Perl5Util preg = new Perl5Util();
preg.substitute(buffer,"s/<script[^>]*?>.*?<\\/script>//gmi",html);
//过滤script标签
html =buffer.toString();
buffer.setLength(0);
preg.substitute(buffer,"s#<[/]*?(?!p|img|span)[^<>]*?>##gmi",html);
//( p/img/span ...标签之外,都删除)
html =buffer.toString();
buffer.setLength(0);
return html;
}
}
上面模板可以根据需求自行更改,也适用于其他情况
补充过滤所有的标签:
text = text.replaceAll("<.*?>", "");
本文介绍两种有效的方法来过滤HTML中的特定标签,如保留img、p和span等,并提供了一个使用正则表达式的简单示例及一个更强大的利用Perl5Util进行多步过滤的例子。适用于前端开发人员快速清除不需要的HTML元素。

213

被折叠的 条评论
为什么被折叠?



