在經典 ASP 中處理用戶輸入時,需移除 HTML 標籤、控制字元(換行、Tab)、多餘空格,並對特殊字元進行實體化編碼,防止 XSS 與排版錯亂。本文提供一個經實戰驗證的 FormatStr 函數。
<%
'===============================================================
' FormatStr - HTML 內容淨化:移除標籤、控制字元、實體化特殊字元
' 參數:str - 待處理字串
' 回傳:淨化後字串
'===============================================================
Function FormatStr(str)
Dim s1, s2, cleaned
If str = "" Then
FormatStr = ""
Exit Function
End If
cleaned = Trim(str)
' 1. 移除雙空格與 Tab
cleaned = Replace(Replace(cleaned, Chr(32) & Chr(32), ""), Chr(9), "")
' 2. 移除所有 HTML 標籤 (<...>)
Do While (InStr(cleaned, "<") > 0 And InStr(cleaned, ">") > 0)
s1 = InStr(cleaned, "<")
s2 = InStr(s1, cleaned, ">")
If s1 > 0 And s2 > 0 Then
cleaned = Replace(cleaned, Mid(cleaned, s1, s2 - s1 + 1), "")
Else
Exit Do
End If
Loop
' 3. 實體化剩餘的 < > 引號 空格
cleaned = Replace(Replace(cleaned, "<", "<"), ">", ">")
cleaned = Replace(Replace(Replace(Replace(Replace( _
cleaned, _
Chr(13), ""), _ ' CR
Chr(10), ""), _ ' LF
"""", "”"), _ ' 雙引號 → 右雙引號實體
"'", "’"), _ ' 單引號 → 右單引號實體
" ", " ") ' 空格 → 不換行空格
FormatStr = cleaned
End Function
%>
| 處理項目 | 處理方式 | 代碼片段 |
|---|---|---|
| 前後空白 | 修剪 | Trim(str) |
| 連續空格 | 移除 | Replace(..., Chr(32)&Chr(32), "") |
| Tab 字元 | 移除 | Replace(..., Chr(9), "") |
| HTML 標籤 | 全移除 | Do While InStr(...) ... Loop |
| 換行符 (CR/LF) | 移除 | Replace(..., Chr(13), "") / Chr(10) |
| < > | 實體化 | < → <; > → > |
| 雙引號 " | 實體化 | ” (或 ") |
| 單引號 ' | 實體化 | ’ (或 ') |
| 空格 | 不換行空格 | |
<%
Dim userInput, safeOutput
userInput = " Hello World" & vbCrLf & "Second line"
safeOutput = FormatStr(userInput)
Response.Write "原始:" & Server.HTMLEncode(userInput) & "
"
Response.Write "淨化:" & safeOutput
%>
輸出:
原始:<script>alert('xss')</script> Hello World
Second line
淨化:alert’xss’ Hello WorldSecond line
若需保留 <b>, <i>, <br> 等安全標籤,建議改用正則表達式或引入 Microsoft HTML Object Library (MSHTML) 進行 DOM 級淨化。簡易版正則:
Function SafeHtml(str)
Dim re, allowedTags
Set re = New RegExp
re.Global = True
re.IgnoreCase = True
' 移除非白名單標籤
allowedTags = "b|i|u|br|p|strong|em"
re.Pattern = "?(?!" & allowedTags & "\b)[^>]+>"
SafeHtml = re.Replace(str, "")
' 實體化剩餘 < >
SafeHtml = Replace(Replace(SafeHtml, "<", "<"), ">", ">")
Set re = Nothing
End Function
AntiXSS Library (ASP.NET)、DOMPurify (前端)、HTML Purifier (PHP)。FormatStr 移除所有標籤較激進,適用於「純文字輸出」場景(如列表標題、JSON 字串值)。