如题,  比如留言之类的我要过滤一些关键字,这个该怎么做,给个实例

解决方案 »

  1.   

    客户端的过滤没有什么实际作用
    在后台设置过滤字符
    void Application_BeginRequest(object sender, EventArgs e)
    {
      for (int i=0; i < Request.Form.Count;i++)
      {
      if (Request.Form[i].ToString() == "__VIEWSTATE") continue;
      if (IsM(Request.Form[i].ToString()))
      {
      Response.Write("您提交的内容中含有非法字符.");
      Response.End();
      }  }   
    }
    protected bool IsM(string InText)
    {
      string word = @"";
      if (InText == null)
      return false;
      if (Regex.IsMatch(InText,word))
      return true;
      return false;
    }   
      

  2.   

    看下面(关键字放在数据库中,SQLHelper为操作数据库类)public static string Filtrator(string str)
            {
                string message = str;
                string badWord;
                string sqlStr = "select top 1 forbidword_Word from ForbidWords";
                SqlDataReader sdr = SQLHelper.ReturnDataReader(sqlStr);
                if (sdr.Read())
                {
                    badWord = sdr["forbidword_Word"].ToString();
                }
                else
                {
                    badWord = "";
                }
                if (badWord != null)
                {
                    string[] badWordArray = badWord.Split('|');
                    for (int i = 0; i < badWordArray.Length; i++)
                    {
                        message = message.Replace(badWordArray[i],"*");
                    }
                    return message;
                }
                else
                {
                    return message;
                }
            }
      

  3.   


        public static string badword(string str)//str要过滤的关键字
        {
            SqlConnection conn = new SqlConnection(db.connDB());
            conn.Open();
            string sql = "select Sys_BadWord from Sys";
            SqlCommand cmd = new SqlCommand(sql, conn);
            string badstr=Convert.ToString(cmd.ExecuteScalar());//badstr过滤字符 如“操你妈|我草” 用“|”隔开
            conn.Close();
            conn.Dispose();
            string[] sArray=badstr.Split('|');//"|"分离
            foreach (string i in sArray)
        {
                str = str.Replace(i, "***");//将字符过滤成“***”
        }
            return str;
        }