過濾HTML標籤,這個應該可以列為大部分專案都可能會需要用到的,

就算不會用到,也可以收藏到自己的程式庫。

 

有時候網頁使用編輯器提供使用者輸入資料,此時資料庫裏面就會有HTML的標籤

再加上使用者會有匯出文件的需求

 

若是匯出Excel,則會將HTML的標籤完整顯示出來,這樣的結果使用者一定是無法接收的,

所以我們才會需要將HTML濾掉。

 

程式如下,前半段就是在做過濾的動作

後面有一段"另外新增要取代的",這個部分是為了使用者輸入有時候可能會有引號、大於、小於之類的符號,

我們不能讓它一起被取代掉,所以需要再另外處理

 

image

 

文字的程式如下~

    public static String delHTMLTag(String htmlStr) {
        String regEx_script = "<script[^>]*?>[//s//S]*?<///script>"; // 定義script的正則表示式
        String regEx_style = "<style[^>]*?>[//s//S]*?<///style>"; // 定義style的正則表示式
        String regEx_html = "<[^>]+>"; // 定義HTML標籤的正則表示式

        Pattern p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
        Matcher m_script = p_script.matcher(htmlStr);
        htmlStr = m_script.replaceAll(""); // 過濾script標籤

        Pattern p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
        Matcher m_style = p_style.matcher(htmlStr);
        htmlStr = m_style.replaceAll(""); // 過濾style標籤

        Pattern p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
        Matcher m_html = p_html.matcher(htmlStr);
        htmlStr = m_html.replaceAll(""); // 過濾html標籤

        // 另外新增要取代的
        htmlStr = htmlStr.replace("&nbsp;", "");
        htmlStr = htmlStr.replace("&lt;", "<");
        htmlStr = htmlStr.replace("&gt;", ">");
        htmlStr = htmlStr.replace("&quot;", "\"");
        htmlStr = htmlStr.replace("&apos;", "'");

        return htmlStr.trim(); // 返回文字字串
    }

 

arrow
arrow
    文章標籤
    JAVA HTML 過濾HTML
    全站熱搜

    我的暱稱 發表在 痞客邦 留言(0) 人氣()