去掉文本中的html标签

简介: 去掉文本中的html标签
+关注继续查看

/**
     * 去掉文本中的html标签
     *
     * @param inputString
     * @return
     */
    public static String html2Text(String inputString) {
        if (StringUtils.isEmpty(inputString)) {
            return null;
        }
        String htmlStr = inputString;
        String textStr = "";
        java.util.regex.Pattern p_script;
        java.util.regex.Matcher m_script;
        java.util.regex.Pattern p_style;
        java.util.regex.Matcher m_style;
        java.util.regex.Pattern p_html;
        java.util.regex.Matcher m_html;

        java.util.regex.Pattern p_html1;
        java.util.regex.Matcher m_html1;

        try {
            String regEx_script = "<[\\s]*?script[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?script[\\s]*?>"; // 定义script的正则表达式{或<script[^>]*?>[\\s\\S]*?<\\/script>
            // }
            String regEx_style = "<[\\s]*?style[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?style[\\s]*?>"; // 定义style的正则表达式{或<style[^>]*?>[\\s\\S]*?<\\/style>
            // }
            String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式
            String regEx_html1 = "<[^>]+";
            p_script = Pattern.compile(regEx_script,
                    Pattern.CASE_INSENSITIVE);
            m_script = p_script.matcher(htmlStr);
            htmlStr = m_script.replaceAll(""); // 过滤script标签

            p_style = Pattern
                    .compile(regEx_style, Pattern.CASE_INSENSITIVE);
            m_style = p_style.matcher(htmlStr);
            htmlStr = m_style.replaceAll(""); // 过滤style标签

            p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
            m_html = p_html.matcher(htmlStr);
            htmlStr = m_html.replaceAll(""); // 过滤html标签

            p_html1 = Pattern
                    .compile(regEx_html1, Pattern.CASE_INSENSITIVE);
            m_html1 = p_html1.matcher(htmlStr);
            htmlStr = m_html1.replaceAll(""); // 过滤html标签

            textStr = htmlStr;

            // 替换&amp;nbsp;
            textStr = textStr.replaceAll("&amp;", "").replaceAll("nbsp;", "");

        } catch (Exception e) {
            System.err.println("Html2Text: " + e.getMessage());
        }

        return textStr;// 返回文本字符串
    }
目录
相关文章
|
18天前
|
移动开发 安全 JavaScript
HTML——标签,属性,语法总结
HTML——标签,属性,语法总结
|
30天前
fastadmin框架获取富文本内容(不过滤HTML标签)
fastadmin框架获取富文本内容(不过滤HTML标签)
20 0
|
1月前
HTML基础(二)列表标签
HTML基础(二)列表标签
|
1月前
|
数据采集 移动开发 搜索推荐
HTML 元素标签语义化及使用场景
HTML 元素标签语义化及使用场景
37 0
|
1月前
|
前端开发 JavaScript
React 解析html标签
React 解析html标签
28 0
|
1月前
|
前端开发 数据安全/隐私保护
常用HTML标签大全
常用HTML标签大全
39 0
|
1月前
|
移动开发 前端开发 搜索推荐
[HTML]HTML5新增标签
[HTML]HTML5新增标签
|
1月前
|
安全 UED
HTML <iframe> 标签的常用属性--详解(附加代码)
HTML <iframe> 标签的常用属性--详解(附加代码)
|
1月前
|
UED
HTML中a标签的target属性的取值和作用--详解(附加代码)
HTML中a标签的target属性的取值和作用--详解(附加代码)
|
1月前
|
PHP
PHP - Laravel 未转义输出,输出 HTML 标签到页面展示({!! $变量 !!})
PHP - Laravel 未转义输出,输出 HTML 标签到页面展示({!! $变量 !!})
25 0
推荐文章
更多