Web 浏览器中区分大小写

我在下面有这些代码,它可以识别您使用 Web 浏览器控件输入的坏词(这些词存储在数据库中)并将其转换为星号 (*)。我一直在努力区分大小写,您可以在其中输入小写或大写(例如:HeLlo)


    string query;

    query = @"select Word from ListWords";


    List<string> words = new List<string>();


    DataSet ds;

    DataRow drow;


    ds = DatabaseConnection.Connection1(query);

    int index, total;


    total = ds.Tables[0].Rows.Count;


    string current_word;


    for (index = 0; index < total; index++ )

    {

        drow = ds.Tables[0].Rows[index];

        current_word = drow.ItemArray.GetValue(0).ToString();


        words.Add(current_word);

    }


    Console.WriteLine(query);



    Console.WriteLine("array:" + words);

    foreach (String key in words)

    {

        String substitution = "<span style='background-color: rgb(255, 0, 0);'>" + key + "</span>";


        int len = key.Length;

        string replace = "";


        for ( index = 0; index < len; index++)

        {

            replace += "*";

        }


        html.Replace(key, replace);

        //count++;

    }



    doc2.body.innerHTML = html.ToString();

}


白衣非少年
浏览 229回答 1
1回答

胡说叔叔

如果我理解正确,您想在html字符串中搜索过滤器列表中的单词,并将它们替换为一些HTML编码字符串加上*代替“坏词”。Regex 是一个很好的解决方案。所以假设你有一个这样的单词列表:List<string> badWords = new List<string>{&nbsp; &nbsp; "Damn",&nbsp; &nbsp; "Hell",&nbsp; &nbsp; "Idiot"};这是你的HTML。var html = "You're a damn idIOT!!";好吧,不是很多HTML,但请耐心等待。现在您遍历单词列表,我们Regex为每个单词创建一个忽略大小写的单词。然后根据单词的长度,我们创建一个替换字符串。然后调用Regex.Replace()。foreach (var word in badWords){&nbsp; &nbsp; Regex rgx = new Regex(word, RegexOptions.IgnoreCase);&nbsp; &nbsp; var blocked = new string('*', word.Length);&nbsp; &nbsp; var replacement = "<span style='background-color: rgb(255, 0, 0);'>" + blocked + "</span>";&nbsp; &nbsp; html = rgx.Replace(html, replacement);}编辑此外,您实际上并不需要重新发明轮子。这是一篇关于亵渎过滤器的精彩 SO 帖子。
打开App,查看更多内容
随时随地看视频慕课网APP