在建立文章列表、RSS 輸出或搜尋預覽時,常需從富文本內容中剝離 HTML 標籤(特別是 <img>、<a> 等),只保留純文字摘要。本文示範使用 VBScript RegExp 物件達成此目標。
<%
Function StripHTML(htmlStr)
Dim re, result
Set re = New RegExp
re.Global = True
re.IgnoreCase = True
' 移除所有 HTML 標籤(含屬性)
re.Pattern = "<[^>]+>"
result = re.Replace(htmlStr, "")
' 解碼常見 HTML 實體
result = Replace(result, " ", " ")
result = Replace(result, "<", "<")
result = Replace(result, ">", ">")
result = Replace(result, """, """")
result = Replace(result, "&", "&")
' 壓縮多餘空白
re.Pattern = "\s+"
result = re.Replace(result, " ")
StripHTML = Trim(result)
End Function
%>
<%
Dim rawContent, plainText
rawContent = "<p>歡迎來到<a href='https://example.com'>範例網站</a>!<img src='logo.png' alt='Logo'></p>"
plainText = StripHTML(rawContent)
Response.Write "原始:" & rawContent & "<br>"
Response.Write "純文字:" & plainText
' 輸出:歡迎來到範例網站!
%>
若需保留 <p>、<br> 等排版標籤,僅移除圖片與連結:
Function RemoveImgAndLinks(htmlStr)
Dim re
Set re = New RegExp
re.Global = True
re.IgnoreCase = True
' 移除
re.Pattern = "<img[^>]*>"
htmlStr = re.Replace(htmlStr, "")
' 移除 ... 但保留內文
re.Pattern = "<a[^>]*>([\s\S]*?)</a>"
htmlStr = re.Replace(htmlStr, "$1")
RemoveImgAndLinks = htmlStr
End Function
RegExp 物件建立為 Application 或 Session 層級的單例,避免重複 New RegExp 的開銷。HTMLParser COM 物件)或離線預處理。<%@ Language=VBScript %>
<html><head><title>HTML 標籤移除測試</title></head><body>
<%
Function StripHTML(htmlStr)
Dim re, result
Set re = New RegExp
re.Global = True
re.IgnoreCase = True
re.Pattern = "<[^>]+>"
result = re.Replace(htmlStr, "")
result = Replace(result, " ", " ")
result = Replace(result, "<", "<")
result = Replace(result, ">", ">")
result = Replace(result, """, """")
result = Replace(result, "&", "&")
re.Pattern = "\s+"
result = re.Replace(result, " ")
StripHTML = Trim(result)
End Function
Dim testStr
testStr = "<div class='box'><h2>標題</h2><p>內容<a href='#'>連結</a><img src='x.jpg'></p></div>"
%>
<fieldset><legend>原始 HTML</legend>
<pre><%=Server.HTMLEncode(testStr)%></pre>
</fieldset>
<fieldset><legend>移除標籤後</legend>
<pre><%=StripHTML(testStr)%></pre>
</fieldset>
</body></html>