限制用户输入某些语言。

时间:2012-07-14 17:08:49

标签: c# asp.net

我正在创建一个包含用户评论区域的网站。留言簿或产品评论示例。我想限制用户在评论区域发布不适当的语言。例如:粗俗。

如果用户输入任何粗俗,则字符将替换为*。 *示例 - 从愚蠢到s * * * * **。

我一直在研究相关网站,但它没有用。对此的建议或教程将不胜感激。

1 个答案:

答案 0 :(得分:-1)

没有办法完全阻止使用“坏语言”,但你可以尝试通过创建一个包含每行中一个坏词的文本文件来阻止它。然后将文件中的单词列表加载到程序中的List<String>。您可以通过执行以下操作来执行此操作:

// The list of swear words
List<string> swearWords = new List<string>();

private void GetSwearWords()
{
    // Get the path to the file that has the swear words list
    string path = <File Path>;

    // Open the text file
    TextReader reader = new StreamReader(path);

    // Loop through each line in the file.
    string line = "";
    while ((line = reader.ReadLine()) != null)
    {
       // Lower cases word and removes whitespaces
       string word = line.Trim().ToLower();

       // Adds the word to the list
       swearWords.Add(word);
    }
}

然后,要确定字符串是否包含其中一个坏词,请执行以下操作:

private bool HasSwearWord(string text)
{
    // Splits words, removes whitespace and any punctuation
    string[] wordArray = Regex.Split(text, @"\W+");

    // Check if any word in the string is a swear word
    foreach (string word in wordArray)
    {
        if (swearWords.Contains(word.ToLower()))
        {
            return true;
        }
    }
    return false;
}
相关问题