萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> HTML5 教學

用正則表達式過濾 HTML 標籤:VBScript/ASP 經典實作

在伺服器端(ASP/VBScript)或客戶端需要移除 HTML 標籤、僅保留純文字時,正則表達式是最直接的工具。本文提供完整的 VBScript 函式 stripHTML,示範如何移除標籤、轉義實體字元,並附上測試表單頁面。

核心函式 stripHTML(strHTML)

<%
Option Explicit

Function stripHTML(strHTML)
  ' 移除 HTML 標籤,回傳純文字
  Dim objRegExp, strOutput
  Set objRegExp = New RegExp
  objRegExp.IgnoreCase = True
  objRegExp.Global = True
  objRegExp.Pattern = "<.+?>"  ' 非貪婪匹配所有標籤

  ' 替換標籤為空字串
  strOutput = objRegExp.Replace(strHTML, "")

  ' 轉義殘留的 < > 實體
  strOutput = Replace(strOutput, "<", "<")
  strOutput = Replace(strOutput, ">", ">")

  Set objRegExp = Nothing
  stripHTML = strOutput
End Function
%>

測試頁面完整代碼

<form method="post" id="form1" name="form1">
  <b>Enter an HTML String:</b><br>
  <textarea name="txtHTML" cols="50" rows="8" wrap="virtual"><%=Request("txtHTML")%></textarea>
  <p>
  <input type="submit" value="Strip HTML Tags!" id="submit1" name="submit1">
</form>

<% If Len(Request("txtHTML")) > 0 Then %>
  <p><hr><p>
  <b><u>View of string <i>with no</i> HTML stripping:</u></b><br>
  <xmp><%=Request("txtHTML")%></xmp><p>
  <b><u>View of string <i>with</i> HTML stripping:</u></b><br>
  <pre><%=StripHTML(Request("txtHTML"))%></pre>
<% End If %>

正則模式解析

  • <.+?>:非貪婪匹配 < 到最近的 >,涵蓋單標籤(<br>)、雙標籤(<div>...</div>)、帶屬性標籤。
  • IgnoreCase = True:大小寫不敏感,匹配 <DIV> 等。
  • Global = True:全域替換所有匹配。

已知限制與改進方向

問題說明改進建議
Script/Style 內容未移除正則會保留 <script>code</script> 中的 code先以 <script[\s\S]*?</script> 移除再跑主正則
註解未移除<!-- comment --> 會被保留加入 <!--[\s\S]*?--> 模式
條件註釋IE 條件註釋 <![if IE]>...<![endif]> 未處理加入專用模式或使用 HTML 解析器
編碼實體未解碼&nbsp;, &amp; 等保持原樣配合 Server.HTMLDecode 或實體對照表解碼
巢狀標籤邊界極複雜巢狀可能誤判嚴謹場景請用 DOMParser (客戶端) 或 HTML Agility Pack (伺服端 .NET)

現代替代方案(客戶端 JavaScript)

function stripHTML(str) {
  const div = document.createElement('div');
  div.innerHTML = str;
  return div.textContent || div.innerText || '';
}

// 或使用 DOMParser(支援 SVG/MathML)
function stripHTML2(str) {
  const doc = new DOMParser().parseFromString(str, 'text/html');
  return doc.body.textContent || '';
}
現代專案強烈建議使用瀏覽器原生 DOM 解析而非正則,正確率 100% 且自動處理實體解碼、巢狀結構、XSS 風險。
copyright © 萬盛學電腦網 all rights reserved