[ASP]使用Regulare Expression將字串做過濾

有關網頁及相關語法的討論
回覆文章
頭像
tim
文章: 1380
註冊時間: 2008年 11月 26日, 00:49

[ASP]使用Regulare Expression將字串做過濾

文章 tim »

利用 regulare expression 進行字串的過濾, 對於大量的字串過濾非常有用. 先列出函數如下:

Function ReplaceKeyWord(strSource, strPattern, strReplace)
Set objReg = new RegExp
objReg.Pattern = strPattern
objReg.IgnoreCase = True
objReg.Global = True
ReplaceKeyWord = objReg.Replace(strSource, strReplace)
Set objReg = Nothing
End Function

使用方式, 若是過濾特定字串, 如網址, 或人名等:

myString = "this is a 123 string with 456 haha, 1234 is a good man, 34567 is bad man"
myString = ReplaceKeyWord(myString, "123|567", "")

輸出結果為:
this is a string with 456 haha, 4 is a good man, 34 is bad man

若是過濾像是 html 的程式碼時:
myString = "haha < script>alert('123');</script> bi no haha document.write('aaa'); "
myString = ReplaceKeyWord(myString, "<.*script.*>.*<.*/script.*>|document.write", "")

輸出結果為:
haha bi no haha ('aaa');

其中在 regular expression 中的比對字串, 使用 | 符號是 "或" 的意思, 也就代表著 123 或 456 這樣的意義, 若有多組要過濾字, 則都可以同時帶入, 使用上相當便利!
多多留言, 整理文章, 把經驗累積下來.....
回覆文章