zoukankan      html  css  js  c++  java
  • 过滤查询条件LIKE里面的关键字符

     /// <summary>
    /// 消除用户录入的恶意字符串。用户录入的查询条件应先用此函数过滤
    /// </summary>
    /// <param name="text">用户录入的字符串</param>
    /// <param name="maxLength">字符串的最大长度</param>
    /// <returns>清除恶意字符串后的结果</returns>
    public static string InputText(string text, int maxLength)
    {
    text
    = text.Trim();
    if (string.IsNullOrEmpty(text))
    return string.Empty;
    if (text.Length > maxLength)
    text
    = text.Substring(0, maxLength);
    text
    = Regex.Replace(text, "[\\s]{2,}", " "); //two or more spaces
    text = Regex.Replace(text, "(<[b|B][r|R]/*>)+|(<[p|P](.|\\n)*?>)", "\n"); //<br>
    text = Regex.Replace(text, "(\\s*&[n|N][b|B][s|S][p|P];\\s*)+", " "); //&nbsp;
    text = Regex.Replace(text, "<(.|\\n)*?>", string.Empty); //any other tags
    text = text.Replace("'", "''");

    /*我们都知道SQL Server查询过程中,单引号“'”是特殊字符,所以在查询的时候要转换成双单引号“''”。
    但这只是特殊字符的一个,在实际项目中,发现对于like操作还有以下特殊字符:下划线“_”,百分号“%”,方括号“[]”以及尖号“^”。
    在实际进行处理的时候,对于=操作,我们一般只需要如此替换:
    ' -> ''
    对于like操作,需要进行以下替换(注意顺序也很重要)
    [ -> [[] (这个必须是第一个替换的!!)
    % -> [%] (这里%是指希望匹配的字符本身包括的%而不是专门用于匹配的通配符)
    _ -> [_]
    ^ -> [^]
    */
    text
    = text.Replace("[", "[[]");
    text
    = text.Replace("%", "[%]");
    text
    = text.Replace("_", "[_]");
    text
    = text.Replace("[^]", "[[^]]");
    return text;
    }
    
    
  • 相关阅读:
    Linux上查找
    Linux进程
    Linux重定向
    Linux上常用的基本命令
    LInux上返回到切换目录前的目录
    【网络知识之一】4/7层网络模型
    【操作系统之十五】iptables黑白名单、自定义链、网络防火墙、常用动作
    【操作系统之十四】iptables扩展模块
    【操作系统之十三】Netfilter与iptables
    【操作系统之十二】分支预测、CPU亲和性(affinity)
  • 原文地址:https://www.cnblogs.com/shineqiujuan/p/1336611.html
Copyright © 2011-2022 走看看