在留言板、論壇、表單送出前,將使用者輸入中的敏感/違禁詞彙替換為 *** 或其他遮罩字元,維護社群環境。
<%
Function FilterBadWords(inputStr)
' 違禁詞清單,以 | 分隔,實務建議存資料庫或外部設定檔
Dim badWordsList, badWords, i, result
badWordsList = "不雅詞1|不雅詞2|敏感詞|廣告詞|惡意字串"
badWords = Split(badWordsList, "|")
result = inputStr
For i = 0 To UBound(badWords)
If InStr(result, badWords(i)) > 0 Then
' 不區分大小寫替換 (VBScript Replace 預設區分大小寫)
' 若需不區分大小寫,需自行迴圈比對或用正則
result = Replace(result, badWords(i), "***", 1, -1, vbTextCompare)
End If
Next
FilterBadWords = result
End Function
' 使用範例
Dim userInput, cleanInput
userInput = Request.Form("content")
cleanInput = FilterBadWords(userInput)
Response.Write "過濾後:" & cleanInput
%>
Class BadWordFilter
Private dict, regex
Private Sub Class_Initialize()
Set dict = CreateObject("Scripting.Dictionary")
Set regex = New RegExp
regex.Global = True
regex.IgnoreCase = True
LoadWordList Server.MapPath("/data/badwords.txt")
End Sub
Sub LoadWordList(filePath)
Dim fso, f, line, words, i
Set fso = CreateObject("Scripting.FileSystemObject")
If fso.FileExists(filePath) Then
Set f = fso.OpenTextFile(filePath, 1) ' ForReading
Do Until f.AtEndOfStream
line = Trim(f.ReadLine)
If line <> "" And Left(line, 1) <> "#" Then
' 支援正則模式,如 \b(bad|worse)\b
dict(line) = True
End If
Loop
f.Close
End If
End Sub
Function Filter(text, Optional replacement = "***")
Dim pattern, word
pattern = ""
For Each word In dict.Keys
If pattern <> "" Then pattern = pattern & "|"
pattern = pattern & "(" & word & ")"
Next
If pattern = "" Then Filter = text: Exit Function
regex.Pattern = pattern
Filter = regex.Replace(text, replacement)
End Function
Function HasBadWord(text)
HasBadWord = (Filter(text, "|MATCHED|") <> text)
End Function
End Class
' 使用方式
Dim filter, cleanText
Set filter = New BadWordFilter
cleanText = filter.Filter(Request.Form("comment"))
If filter.HasBadWord(Request.Form("comment")) Then
' 記錄違規日誌、扣分、人工審核佇列...
End If
\bword\b 避免誤殺 "classic" 中的 "ass")。regex.IgnoreCase = True。Replace 迴圈。HasBadWord 可觸發額外動作 (記錄、封鎖、審核)。基礎版 Split + Replace 適合簡單專案;進階版 類別封裝 + 正則 + 外部詞庫 才是生產環境可維護、可擴充的解決方案。記住:關鍵字過濾只能擋住已知模式,需配合人工審核與行為分析才能建立完整防護體系。