[Java] html script style 标签过滤类 →→→→→进入此内容的聊天室

来自 , 2020-12-12, 写在 Java, 查看 137 次.
URL http://www.code666.cn/view/55b37c5c
  1. import java.util.regex.Pattern;
  2.  
  3. /**
  4.  * html script style标签过滤类
  5.  */
  6. public class HtmlUtils {
  7.         /**
  8.          *
  9.          * @param content
  10.          *            要转换的字符串
  11.          * @param p
  12.          *            结果的长度
  13.          * @return
  14.          */
  15.         public static String getNoHTMLString(String content, int p) {
  16.  
  17.                 if (null == content)
  18.                         return "";
  19.                 if (0 == p)
  20.                         return "";
  21.  
  22.                 java.util.regex.Pattern p_script;
  23.                 java.util.regex.Matcher m_script;
  24.                 java.util.regex.Pattern p_style;
  25.                 java.util.regex.Matcher m_style;
  26.                 java.util.regex.Pattern p_html;
  27.                 java.util.regex.Matcher m_html;
  28.  
  29.                 try {
  30.                         String regEx_script = "<[\\s]*?script[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?script[\\s]*?>";
  31.                         // 定义script的正则表达式{或<script[^>]*?>[\\s\\S]*?<\\/script> }
  32.                         String regEx_style = "<[\\s]*?style[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?style[\\s]*?>";
  33.                         // 定义style的正则表达式{或<style[^>]*?>[\\s\\S]*?<\\/style> }
  34.                         String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式
  35.  
  36.                         p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
  37.                         m_script = p_script.matcher(content);
  38.                         content = m_script.replaceAll(""); // 过滤script标签
  39.  
  40.                         p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
  41.                         m_style = p_style.matcher(content);
  42.                         content = m_style.replaceAll(""); // 过滤style标签
  43.  
  44.                         p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
  45.                         m_html = p_html.matcher(content);
  46.  
  47.                         content = m_html.replaceAll(""); // 过滤html标签
  48.                 } catch (Exception e) {
  49.                         return "";
  50.                 }
  51.  
  52.                 if (content.length() > p) {
  53.                         content = content.substring(0, p) + "...";
  54.                 }
  55.                 return content;
  56.         }
  57.  
  58. }

回复 "html script style 标签过滤类"

这儿你可以回复上面这条便签

captcha