萬盛學電腦網

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

ASP 過濾違禁字串函式:簡易關鍵字替換實作

函式目的

在留言板、論壇、表單送出前,將使用者輸入中的敏感/違禁詞彙替換為 *** 或其他遮罩字元,維護社群環境。

核心程式碼

<%
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

關鍵改進點

  1. 外部化詞庫:文字檔/資料庫維護,無需改程式碼重新部署。
  2. 正則支援:可處理變體、邊界匹配 (如 \bword\b 避免誤殺 "classic" 中的 "ass")。
  3. 不區分大小寫:regex.IgnoreCase = True。
  4. 效能:單次正則替換取代多次 Replace 迴圈。
  5. 偵測功能:HasBadWord 可觸發額外動作 (記錄、封鎖、審核)。

部署建議

  • 詞庫檔案置於 Web 根目錄外,防止直接下載。
  • 定期更新詞庫,結合使用者回報機制。
  • 前端 JS 同步過濾可提升使用者體驗,但後端必須二次驗證。
  • 考慮引入第三方服務 (如 Perspective API) 進行語意級毒性偵測。

總結

基礎版 Split + Replace 適合簡單專案;進階版 類別封裝 + 正則 + 外部詞庫 才是生產環境可維護、可擴充的解決方案。記住:關鍵字過濾只能擋住已知模式,需配合人工審核與行為分析才能建立完整防護體系。

copyright © 萬盛學電腦網 all rights reserved