前段時間在公司做了一個論壇屏蔽關鍵字的功能,我做的比較簡單、實用~ 現在拿出來給博友們分享下..也希望大家能頂頂我~
建立一個txt的文本 . (代碼中讀取這個文字文件路徑就行,命名隨意)
裡面的內容一行代表一個,因為我是按行來遍曆迴圈讀取要屏蔽的關鍵字.然後用一個*號來屏蔽一個關鍵字,
例如: 在論壇中輸出"草泥馬",涉及到一些比較敏感的話題、名字,在一些推廣比較火爆的網站裡,都是不允許的,所以這裡會只顯示"***"。
這裡代碼下面我給出來了,注釋都比較詳細..不懂的可以留言問我.希望博友每天能進步一點點..
/// <summary>
/// 屏蔽非法字串(如果有出現非法字元,那麼用"***"來替換)
/// </summary>
/// <param name="strText">要檢測的字串</param>
/// <returns>返還一個健康的字元</returns>
public static string CheckKeyword(string strText)
{
IList<string> list = new List<string>(); //執行個體化一個資料集
string strpath = System.Web.HttpContext.Current.Server.MapPath("function/keyword.txt"); //擷取文字文件路徑
int a =strpath.LastIndexOf("IFSns");
int b =strpath.IndexOf("function");
string m = strpath.Substring(a+5, b - a - 6);
string PathTxt = strpath.Replace(m, ""); //擷取調用這個方法的相對路徑
FileStream fs = new FileStream(PathTxt, FileMode.Open, FileAccess.Read); //開啟txt文檔,將資料存到檔案流中
StreamReader reader = new StreamReader(fs, Encoding.Default); //檔案讀取
string strLine = reader.ReadLine();
while (strLine!=null&&strLine.Length != 0) //有資料
{
list.Add(strLine.Trim().Replace(" ","")); //如果讀取到的資料有空格,則刪除空格,並且存到string資料集中
strLine = reader.ReadLine(); //每讀取一次,從該行下一行開始繼續讀取
}
fs.Close(); //關閉檔案流
foreach (string str in list) //迴圈遍曆檔案流
{
if (strText.Contains(str))
{
int lg = str.Length;
string sg = "";
for (int i = 0; i < lg; i++)
{
sg+="*";
}
strText = strText.Replace(str, sg); //如果含有txt文檔中的關鍵字,則替換為"***"
}
}
return strText;
}
記:Darren