过滤非法字符

    技术2022-05-18  10

    /// <summary>过滤脏字将字体替换        /// </summary>        /// <param name="text"></param>        /// <returns></returns>        public static string FilterKeyWord(string text, string repStr)        {            string input = text;            for (int i = 0; i < repStr.Split('').Length; i++)            {                MatchCollection matches = null;                string temp = protectHtml(input, ref matches);                temp = Filter(temp, repStr.Split('')[i]);                input = restoreHtml(temp, matches);            }            return input;        } private static string protectHtml(string input, ref MatchCollection matches)        {            //匹配html的正则            Regex htmlReg =                new Regex(@"/<.*?/>", RegexOptions.Multiline);            //获取匹配集合            matches = htmlReg.Matches(input);            //设置替换字串            string markFormat = "[[{0}]]";            //替换html,记录位置            for (int i = 0; i < matches.Count; i++)            {                input = input.Replace(matches[i].Value, string.Format(markFormat, i));            }            return input;        } private static string restoreHtml(string input, MatchCollection matches)        {            //设置替换字串            string markFormat = "[[{0}]]";            for (int i = 0; i < matches.Count; i++)            {                input = input.Replace(string.Format(markFormat, i), matches[i].Value);            }            return input;        } private static string Filter(string input, string replace)        {            //设置星号            string replaceformat = "*";            Regex reg = new Regex(String.Format("{0}", replace), RegexOptions.Multiline);            return reg.Replace(input, string.Format(replaceformat, replace));        }调用 string badStr = "<p>adfsf变化色和sss性<a href='#?id=2008'>年份</a></p>";Response.Write("<br/>" + FilterKeyWord(badStr , new Config().Badtext));一般把脏话写在xml,new Config().Badtext这个我就不具体,楼主测试时候Response.Write("<br/>" + FilterKeyWord(badStr ,"色|性" ));


    最新回复(0)