萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP 程式設計

ASP 移除所有 HTML 標籤函式:RegExp 純文字提取實作

函式功能

將字串中所有 HTML 標籤 (``, ``, `` 等) 移除,僅保留純文字內容。常用於:摘要產生、搜尋索引、純文字郵件、資料匯出。

核心實作

<%
Function StripHtmlTags(htmlStr)
    Dim regex, result
    If IsNull(htmlStr) Or htmlStr = "" Then
        StripHtmlTags = htmlStr
        Exit Function
    End If
    
    Set regex = New RegExp
    regex.Pattern = "<[^>]*>"     ' 匹配 < 開頭,非 > 任意字元,> 結尾
    regex.Global = True           ' 替換所有匹配
    regex.IgnoreCase = True       ' 不區分大小寫 (標籤名)
    
    result = regex.Replace(htmlStr, "")
    Set regex = Nothing
    
    ' 選項:將多個連續空白/換行壓縮為單一空白
    result = Replace(result, " ", " ")
    result = Replace(result, vbCrLf, " ")
    result = Replace(result, vbCr, " ")
    result = Replace(result, vbLf, " ")
    ' 進階:正則壓縮空白 (需額外 RegExp)
    ' Set regex = New RegExp: regex.Pattern = "\s+": regex.Global = True: result = regex.Replace(result, " ")
    
    StripHtmlTags = Trim(result)
End Function

' 使用範例
Dim html, plain
html = "

標題

內容
換行

" plain = StripHtmlTags(html) Response.Write plain ' 輸出: 標題 內容 換行 %>

正則模式 `<[^>]*>` 解析

  • `<`:匹配字面 `<` 字元。
  • `[^>]*`:匹配**非 `>` 字元**零或多次 (貪婪)。確保不跨越標籤邊界。
  • `>`:匹配字面 `>` 字元。
  • 可匹配:`
    `, `

    `, ``, `
    `, `` (註解也被視為標籤移除)。

進階需求與擴充

1. 保留特定標籤 (如 ``, ``, ``)


Function StripHtmlExceptAllowed(htmlStr, allowedTags)
    ' allowedTags: "b,i,a,br,p" 逗號分隔
    ' 實作較複雜,建議用 HTML 解析器 (如 HTML Agility Pack .NET) 或 狀態機解析
    ' 簡易版:先保護允許標籤 → 移除所有 → 還原
    Dim placeholder, tag, tagsArr, i, regex
    tagsArr = Split(allowedTags, ",")
    ' ... 略,建議改用成熟庫
End Function

2. 處理 HTML 實體編碼 (`<`, `&`, `"`)


Function DecodeHtmlEntities(str)
    str = Replace(str, "<", "<")
    str = Replace(str, ">", ">")
    str = Replace(str, "&", "&")
    str = Replace(str, """, """")
    str = Replace(str, "'", "'")
    ' 數值實體 〹 / 😀 需正則解碼
    Dim regex
    Set regex = New RegExp
    regex.Global = True
    regex.Pattern = "&#(\d+);"
    str = regex.Replace(str, GetRef("ChrWFromMatch"))
    regex.Pattern = "&#x([0-9A-Fa-f]+);"
    str = regex.Replace(str, GetRef("ChrWFromHexMatch"))
    Set regex = Nothing
    DecodeHtmlEntities = str
End Function

Function ChrWFromMatch(match, p1, pos, src)
    ChrWFromMatch = ChrW(CLng(p1))
End Function
Function ChrWFromHexMatch(match, p1, pos, src)
    ChrWFromHexMatch = ChrW("&H" & p1)
End Function

3. 取得前 N 字純文字摘要


Function GetPlainSummary(htmlStr, maxLen)
    Dim plain
    plain = StripHtmlTags(htmlStr)
    If Len(plain) > maxLen Then
        plain = Left(plain, maxLen) & "..."
    End If
    GetPlainSummary = plain
End Function

效能與替代方案

方法優點缺點適用場景
RegExp Replace原生、無元件、簡單無法處理巢狀/不完整標籤、效能中等簡單清理、摘要、舊系統
Server.HTMLEncode極快、內建不移除標籤,只編碼顯示輸出防 XSS
MSHTML (DOM 解析)完整 DOM 樹、可精確操作需 COM 元件、較重、單執行緒複雜 HTML 處理、舊 ASP 可用
.NET HtmlAgilityPack / AngleSharp標準、強大、支援 .NET Core需 .NET 環境現代專案、移植專案

總結

`StripHtmlTags` 以 `<[^>]*>` 正則快速移除所有標籤,配合空白壓縮可產生乾淨純文字。但**正則無法正確處理巢狀、破損、CDATA、Script/Style 內容** 等複雜 HTML 結構。重要業務 (如內容管理、郵件模板) 請使用 **HTML 解析器 (DOM/HtmlAgilityPack)**。輸出防 XSS 請用 `Server.HTMLEncode`,而非移除標籤。

copyright © 萬盛學電腦網 all rights reserved