將字串中所有 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
' 輸出: 標題 內容 換行
%>
`, `
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
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 = "([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
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`,而非移除標籤。