萬盛學電腦網

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

ASP 正則表達式移除 HTML 標籤:提取純文字文章摘要

需求背景

在建立文章列表、RSS 輸出或搜尋預覽時,常需從富文本內容中剝離 HTML 標籤(特別是 <img>、<a> 等),只保留純文字摘要。本文示範使用 VBScript RegExp 物件達成此目標。

核心函式:StripHTML

<%
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, "&nbsp;", " ")
    result = Replace(result, "&lt;", "<")
    result = Replace(result, "&gt;", ">")
    result = Replace(result, "&quot;", """")
    result = Replace(result, "&amp;", "&")
    ' 壓縮多餘空白
    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 的開銷。
  • 若內容極大(超過 100KB),考慮改用伺服器端元件(如 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, "&nbsp;", " ")
    result = Replace(result, "&lt;", "<")
    result = Replace(result, "&gt;", ">")
    result = Replace(result, "&quot;", """")
    result = Replace(result, "&amp;", "&")
    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>
copyright © 萬盛學電腦網 all rights reserved