萬盛學電腦網

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

ASP過濾 HTML 標籤四大經典方法:RegExp 正則實戰對比

四種方法核心邏輯對比

方法核心技術特點適用場景
1. HTML Encode/Decode字元實體替換不移除標籤,轉義顯示原始碼內容安全顯示、程式碼展示
2. RegExp 移除 <...>正則 <[^>]*>簡單快速、可能誤傷 < 符號簡單過濾、效能優先
3. RegExp 非貪婪匹配 <.+?>正則 <.+?> + 迴圈替換較精準處理巢狀/屬性一般內容淨化
4. 分開匹配開/閉標籤兩階段正則 <[^<]*> + </[^<]*>嘗試處理不完整標籤髒資料清洗

方法一:HTML Encode / Decode (JScript)

function htmlEncode(text) {
    return text.replace(/&/g, '&amp;')
               .replace(/"/g, '&quot;')
               .replace(//g, '&gt;');
}

function htmlDecode(text) {
    return text.replace(/&amp;/g, '&')
               .replace(/&quot;/g, '"')
               .replace(/&lt;/g, '<')
               .replace(/&gt;/g, '>');
}

方法二:簡單 RegExp 移除 (VBScript)

Function NoHTML(str)
    Dim re
    Set re = New RegExp
    re.IgnoreCase = True
    re.Global = True
    re.Pattern = "<[^>]*>"  ' 匹配 <...>
    NoHTML = re.Replace(str, "")
    Set re = Nothing
End Function

方法三:非貪婪匹配 + 迴圈替換 (VBScript)

Function FilterHTML(strToFilter)
    Dim objRegExp, match, matches
    Set objRegExp = New RegExp
    objRegExp.IgnoreCase = True
    objRegExp.Global = True
    objRegExp.Pattern = "<.+?>"  ' 非貪婪匹配
    
    Set matches = objRegExp.Execute(strToFilter)
    For Each match In matches
        strToFilter = Replace(strToFilter, match.Value, "")
    Next
    
    FilterHTML = strToFilter
    Set objRegExp = Nothing
End Function

方法四:分開處理開/閉標籤 (VBScript)

Function NoHTML(str)
    Dim re
    Set re = New RegExp
    re.IgnoreCase = True
    re.Global = True
    
    ' 先移除開啟標籤 
    re.Pattern = "<[^<]*>"
    str = re.Replace(str, "")
    
    ' 再移除關閉標籤 
    re.Pattern = ""
    str = re.Replace(str, "")
    
    NoHTML = str
    Set re = Nothing
End Function

進階:保留允許標籤 (白名單機制)

Function SafeHTML(str, allowedTags)
    ' allowedTags 如 "b,i,u,br,p,img"
    Dim re, tags, tag, pattern
    Set re = New RegExp
    re.IgnoreCase = True
    re.Global = True
    
    tags = Split(allowedTags, ",")
    For Each tag In tags
        ' 保留該標籤:先佔位符保護
        str = Replace(str, "<" & tag & ">", "[[KEEP_" & tag & "]]")
        str = Replace(str, "", "[[KEEP_/" & tag & "]]")
        ' 處理帶屬性 
        re.Pattern = "<\s*" & tag & "\b[^>]*>"
        str = re.Replace(str, "[[KEEP_" & tag & "_ATTR]]")
    Next
    
    ' 移除所有其他標籤
    re.Pattern = "<[^>]*>"
    str = re.Replace(str, "")
    
    ' 還原保留標籤
    For Each tag In tags
        str = Replace(str, "[[KEEP_" & tag & "]]", "<" & tag & ">")
        str = Replace(str, "[[KEEP_/" & tag & "]]", "")
        str = Replace(str, "[[KEEP_" & tag & "_ATTR]]", "<" & tag & ">") ' 簡化:屬性丟失
    Next
    
    SafeHTML = str
End Function

安全性警示

  • 正則無法完美解析 HTML:巢狀、註解、CDATA、JS 事件屬性 (onclick) 等極難完全處理
  • 生產環境**強烈建議**使用成熟函式庫 (如 HTML Agility Pack 移植版、Server-side sanitizer)
  • 儲存時「過濾」,輸出時「編碼」雙重防護
  • 富文本編輯器內容建議採用 BBCode/Markdown 儲存,輸出時轉換

四大方法各有取捨,簡單場景用方法二/三,需顯示原始碼用方法一,複雜安全需求請引入專業函式庫。

copyright © 萬盛學電腦網 all rights reserved