通用类 StringHelper 字符串操作方法

/// <summary>
    /// 字符串操作方法
    /// </summary>
    public class StringHelper
    {
        #region SQL 特殊字符过滤,防SQL注入
        /// <summary>
        /// SQL 特殊字符过滤,防SQL注入
        /// </summary>
        /// <param name="contents">检查的SQL语句</param>
        /// <returns></returns>
        public static string SqlFilter( string contents )
        {
            if (!string.IsNullOrEmpty(contents))
            {
                contents = Regex.Replace(contents, " exec | insert | select | delete | update | master | truncate | declare ", "", RegexOptions.IgnoreCase);
                contents = contents.Replace("'", "''");
            }
            return contents;
        }

        #endregion
                
        #region 替换标记内的内容
        /// <summary>
        /// 替换标记内的内容
        /// </summary>
        /// <param name="beginTag">开始标记</param>
        /// <param name="endTag">结束标记</param>
        /// <param name="contents">原始内容</param>
        /// <param name="newContents">替换内容</param>
        /// <returns></returns>
        public static  string ReplaceContent( string beginTag, string endTag, string contents, string newContents )
        {
            contents = Regex.Replace(contents, string.Format("{0}((.|\n)*?){1}", beginTag, endTag), String.Format("{0}\r\n{1}\r\n{2}", beginTag, newContents, endTag), RegexOptions.IgnoreCase);
            return contents;
        }

        /// <summary>
        /// 获得标记内的内容
        /// </summary>
        /// <param name="beginTag">开始标记</param>
        /// <param name="endTag">结束标记</param>
        /// <param name="contents">查找内容</param>
        /// <returns></returns>
        public static string GetContent(string beginTag, string endTag, string contents)
        {
            return Regex.Match(contents, string.Format("{0}((.|\n)*?){1}", beginTag, endTag)).Value;
        }
        #endregion

        #region 清除脚本等内容
        /// <summary>
        /// 清除所有HTML标记
        /// </summary>
        /// <param name="contents"></param>
        /// <returns></returns>
        public static string ClearHtml( string contents )
        {
            contents = Regex.Replace(contents, "<(object|script)(.*?)>((.|\n)*?)</(object|script|)>", " ", RegexOptions.IgnoreCase);
            contents = Regex.Replace(contents, "<!--#(.*?)((.|\n)*?)-->", " ", RegexOptions.IgnoreCase);
            contents = Regex.Replace(contents, "<%(.*?)((.|\n)*?)%>", " ", RegexOptions.IgnoreCase);
            //					Contents = regexp.Replace(Contents, "&(nbsp|quot|copy);", "");
            //					Contents = regexp.Replace(Contents, "<([\s\S])+?>", " ", RegexOptions.IgnoreCase);
            //					Contents = regexp.Replace(Contents, "\W", " ");
            return contents;
        }

        /// <summary>
        /// 清除所有HTML标记
        /// </summary>
        /// <param name="contents"></param>
        /// <returns></returns>
        public static string ClearAllHtml( string contents )
        {
            contents = Regex.Replace(contents, @"<([\s\S])+?>", "", RegexOptions.IgnoreCase);
            contents = Regex.Replace(contents, "&(nbsp|quot|copy);", "", RegexOptions.IgnoreCase);
            contents = Regex.Replace(contents, " ", "", RegexOptions.IgnoreCase);
            return contents;
        }
        #endregion

        #region 代码过滤
        /// <summary>
        /// 代码解释功能,目的是为了防止一些人恶意的提交一些代码,影响系统的安全使用,通过字符转换的方法,防止这种现象的发生
        /// </summary>
        /// <param name="html">要转换的数据字符串</param>
        /// <param name="filter">要过滤掉的单个格式</param>
        /// <returns>替换后的字符</returns>
        /// <remarks>
        /// DecodeFilter 方法是为了防止提交恶意代码而使用的,可以过滤 Script,Table,Class,Style,XML,NAMESPACE,MARQUEE,FONT,Object等标签的内容
        /// </remarks>
        /// <example>
        /// 以下示例演示了如何使用 DecodeFilter 过滤包含Script脚本的内容:<br />
        /// <code>		///		
        ///		str = DecodeFilter(str,"SCRIPT");
        /// </code>
        /// </example>
        public static string DecodeFilter( string html, string filter )
        {
            string str = html;
            Regex r;
            Match m;
            switch ( filter.ToUpper() )
            {
                case "SCRIPT":
                    //不允许使用javascript,vbscript等,事件onclick,ondlbclick等
                    str = Regex.Replace(str, "</?script[^>]*>", "");
                    r = new Regex(@"</?script[^>]*>", RegexOptions.IgnoreCase);
                    for ( m = r.Match(str);m.Success;m = m.NextMatch() )
                    {
                        str = str.Replace(m.Groups[0].ToString(), "");
                    }
                    r = new Regex(@"(javascript|jscript|vbscript|vbs):", RegexOptions.IgnoreCase);
                    for ( m = r.Match(str);m.Success;m = m.NextMatch() )
                    {
                        str = str.Replace(m.Groups[0].ToString(), String.Format("{0}:", m.Groups[1]));
                    }
                    r = new Regex(@"on(mouse|exit|error|click|key)", RegexOptions.IgnoreCase);
                    for ( m = r.Match(str);m.Success;m = m.NextMatch() )
                    {
                        str = str.Replace(m.Groups[0].ToString(), "");
                    }
                    r = new Regex(@"&#", RegexOptions.IgnoreCase);
                    for ( m = r.Match(str);m.Success;m = m.NextMatch() )
                    {
                        str = str.Replace(m.Groups[0].ToString(), "");
                    }
                    break;
                case "TABLE":
                    //不允许使用table,th,td,tr标签
                    str = Regex.Replace(str, "</?table[^>]*>", "");
                    str = Regex.Replace(str, "</?tr[^>]*>", "");
                    str = Regex.Replace(str, "</?th[^>]*>", "");
                    str = Regex.Replace(str, "</?td[^>]*>", "");
                    str = Regex.Replace(str, "</?tbody[^>]*>", "");
                    break;
                case "CLASS":
                    //不允许使用 class= 这样的标签
                    r = new Regex(@"(<[^>]+) class=[^ |^>]*([^>]*>)", RegexOptions.IgnoreCase);
                    for ( m = r.Match(str);m.Success;m = m.NextMatch() )
                    {
                        str = str.Replace(m.Groups[0].ToString(), String.Format("{0} {1}", m.Groups[0], m.Groups[1]));
                    }
                    break;
                case "STYLE":
                    //不允许使用 style= 这样的标签
                    r = new Regex("(<[^>]+) style=\"[^\"]*\"([^>]*>)", RegexOptions.IgnoreCase);
                    for ( m = r.Match(str);m.Success;m = m.NextMatch() )
                    {
                        str = str.Replace(m.Groups[0].ToString(), String.Format("{0} {1}", m.Groups[0], m.Groups[1]));
                    }
                    break;
                case "XML":
                    //不允许使用 xml 标签
                    str = Regex.Replace(str, "<\\?xml[^>]*>", "");
                    break;
                case "NAMESPACE":
                    //不允许使用 <o:p></o:p> 这种格式
                    str = Regex.Replace(str, @"<\/?[a-z]+:[^>]*>", "");
                    break;
                case "FONT":
                    //不允许使用 font 标签,不建议使用
                    str = Regex.Replace(str, "</?font[^>]*>", "");
                    break;
                case "MARQUEE":
                    //不允许使用 marquee 标签,也就没有移动滚动的特殊
                    str = Regex.Replace(str, "</?marquee[^>]*>", "");
                    break;
                case "OBJECT":
                    //不允许 object, param, embed 标签,不能嵌入对象
                    str = Regex.Replace(str, "</?object[^>]*>", "");
                    str = Regex.Replace(str, "</?param[^>]*>", "");
                    str = Regex.Replace(str, "</?embed[^>]*>", "");
                    break;
            }
            return str;
        }
        #endregion

        #region 字符加密
        /// <summary>
        /// SHA1
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string Entrypt( string str )
        {
            return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "sha1");

        }
        /// <summary>
        /// MD5
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string EntryptMD5( string str )
        {
            return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "md5");
        }

        /// <summary>
        /// Base64编码
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string GetBase64Encode(string str)
        {
            return Convert.ToBase64String(System.Text.Encoding.Default.GetBytes(str));
        }

        /// <summary>
        /// Base64解码
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string GetBase64Decode(string str)
        {
            return Encoding.Default.GetString(Convert.FromBase64String(str));
        }
        #endregion        
        
        #region 截取字符
        /// <summary>
        ///  截取字符
        /// </summary>
        /// <param name="content">需要截取的字符</param>
        /// <param name="length">截取长度</param>
        /// <returns></returns>
        public static string TopString( string content, int length )
        {
            string result = string.Empty;           
            if (content.Length > length)            
            {
                int len = content.Length;
                int n = 0;
                for (int i = 0; i <= len - 1; i++)
                {
                    if (i > len) break;
                    char c = Convert.ToChar(content.Substring(i, 1));
                    if (((int)c > 255) || ((int)c < 0))
                       n = n + 2;
                    else
                        n = n + 1;

                    if (n >= length)
                    {
                        result = content.Substring(0, i + 1) + "…";
                        break;
                    }
                    else
                    {
                        result = content;
                    }

                }

            }
            else result = content;

            return result;
        }
        #endregion

        #region 生成一个随机不重复的字符串
        /// <summary>
        /// 生成一个随机不重复的字符串,用于文件命名
        /// </summary>
        /// <returns>返回</returns>
        public static string RadomFileName()
        {
            return Entrypt(DateTime.Now.ToUniversalTime().ToString().Replace("-", "").Replace(":", "").Replace(" ", "") + GetRandomNext(5).ToString());
        }
        #endregion

        #region 随机数
        /// <summary>
        /// 生成小于10位长度的随机数
        /// </summary>
        /// <param name="length"></param>
        /// <returns></returns>
        public static int GetRandomNext( int length )
        {
            if ( length > 9 )
                throw new System.IndexOutOfRangeException("Length的长度不能大于10");
            Guid gu = Guid.NewGuid();
            string str = "";
            for ( int i = 0;i < gu.ToString().Length;i++ )
            {
                if (Validator.IsNumeric(gu.ToString()[i].ToString()) )
                {
                    str += ( ( gu.ToString()[i] ) );
                }
            }
            int guid = int.Parse(str.Replace("-", "").Substring(0, length));
            if ( !guid.ToString().Length.Equals(length) )
                guid = GetRandomNext(length);
            return guid;
        }
        #endregion

        #region 字符URL编码
        public static string UrlEnCode(string str)
        {
            return HttpUtility.UrlEncode(str);
        }
        #endregion

        #region "隐藏IP地址最后一位用*号代替"
        /// <summary>
        /// 隐藏IP地址最后一位用*号代替
        /// </summary>
        /// <param name="Ipaddress">IP地址:192.168.34.23</param>
        /// <returns></returns>
        public static string HidenLastIP(string ip)
        {
            if (ip.Trim() != string.Empty)
            {
                return ip.Substring(0, ip.LastIndexOf(".")) + ".*";
            }
            else return string.Empty;
        }
        #endregion
        
        #region "按字符串位数补0"
        /// <summary>
        /// 按字符串位数补0
        /// </summary>
        /// <param name="CharTxt">字符串</param>
        /// <param name="CharLen">字符长度</param>
        /// <returns></returns>
        public static string FillZero(string CharTxt, int CharLen)
        {
            if (CharTxt.Length < CharLen)
            {
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < CharLen - CharTxt.Length; i++)
                {
                    sb.Append("0");
                }
                sb.Append(CharTxt);
                return sb.ToString();
            }
            else
            {
                return CharTxt;
            }
        }

        #endregion

        #region "正式表达式验证"
        /// <summary>
        /// 正式表达式验证
        /// </summary>
        /// <param name="C_Value">验证字符</param>
        /// <param name="C_Str">正式表达式</param>
        /// <returns>符合true不符合false</returns>
        public static bool CheckRegex(string content, string regex)
        {
            Regex match = new Regex(regex, RegexOptions.Compiled);
            return match.Match(content).Success;
        }
        #endregion
        

       /// <summary>
        /// 从字符串中的尾部删除指定的字符串
       /// </summary>
       /// <param name="sourceString">源内容</param>
       /// <param name="removedString">要移除的字符</param>
       /// <returns></returns>
        public static string Remove(string sourceString, string removedString)
        {
            try
            {
                if (sourceString.IndexOf(removedString) < 0)
                    return sourceString;

                string result = sourceString;
                int lengthOfSourceString = sourceString.Length;
                int lengthOfRemovedString = removedString.Length;
                int startIndex = lengthOfSourceString - lengthOfRemovedString;
                string tempSubString = sourceString.Substring(startIndex);
                if (tempSubString.ToUpper() == removedString.ToUpper())
                {
                    result = sourceString.Remove(startIndex, lengthOfRemovedString);
                }
                return result;
            }
            catch
            {
                return sourceString;
            }
        }

        /// <summary>
        /// 获取拆分符右边的字符串
        /// </summary>
        /// <param name="sourceString"></param>
        /// <param name="splitChar"></param>
        /// <returns></returns>
        public static string RightSplit(string sourceString, char splitChar)
        {
            string result = null;
            string[] tempString = sourceString.Split(splitChar);
            if (tempString.Length > 0)
            {
                result = tempString[tempString.Length - 1].ToString();
            }
            return result;
        }

        /// <summary>
        /// 获取拆分符左边的字符串
        /// </summary>
        /// <param name="sourceString"></param>
        /// <param name="splitChar"></param>
        /// <returns></returns>
        public static string LeftSplit(string sourceString, char splitChar)
        {
            string result = null;
            string[] tempString = sourceString.Split(splitChar);
            if (tempString.Length > 0)
            {
                result = tempString[0].ToString();
            }
            return result;
        }

        /// <summary>
        /// 删除不可见字符
        /// </summary>
        /// <param name="sourceString"></param>
        /// <returns></returns>
        public static string DeleteUnVisibleChar(string sourceString)
        {
            System.Text.StringBuilder sBuilder = new System.Text.StringBuilder(131);
            for (int i = 0; i < sourceString.Length; i++)
            {
                int Unicode = sourceString[i];
                if (Unicode >= 16)
                {
                    sBuilder.Append(sourceString[i].ToString());
                }
            }
            return sBuilder.ToString();
        }

        /// <summary>
        /// 获取数组元素的合并字符串
        /// </summary>
        /// <param name="stringArray"></param>
        /// <returns></returns>
        public static string GetArrayString(string[] stringArray)
        {
            string totalString = null;
            for (int i = 0; i < stringArray.Length; i++)
            {
                totalString = totalString + stringArray[i];
            }
            return totalString;
        }

        /// <summary>
        /// 获取某一字符串在字符串数组中出现的次数
        /// </summary>
        /// <param name="stringArray"></param>
        /// <param name="findString"></param>
        /// <returns></returns>
        public static int GetStringCount(string[] stringArray, string findString)
        {
            int count = -1;
            string totalString = GetArrayString(stringArray);
            string subString = totalString;

            while (subString.IndexOf(findString) >= 0)
            {
                subString = totalString.Substring(subString.IndexOf(findString));
                count += 1;
            }
            return count;
        }

        /// <summary>
        /// 获取某一字符串在字符串中出现的次数
        /// </summary>
        /// <param name="stringArray">原字符串</param>
        /// <param name="findString">匹配字符串</param>
        /// <returns>
        ///     匹配字符串数量
        /// </returns>
        public static int GetStringCount(string sourceString, string findString)
        {
            int count = 0;
            int findStringLength = findString.Length;
            string subString = sourceString;

            while (subString.IndexOf(findString) >= 0)
            {
                subString = subString.Substring(subString.IndexOf(findString) + findStringLength);
                count += 1;
            }
            return count;
        }

       /// <summary>
        ///  截取从startString开始到原字符串结尾的所有字符   
       /// </summary>
       /// <param name="sourceString"></param>
       /// <param name="startString"></param>
       /// <returns></returns>
        public static string GetSubString(string sourceString, string startString)
        {
            try
            {
                int index = sourceString.ToUpper().IndexOf(startString);
                if (index > 0)
                {
                    return sourceString.Substring(index);
                }
                return sourceString;
            }
            catch
            {
                return "";
            }
        }

        /// <summary>
        /// 截取字符串里面的字母
        /// </summary>
        /// <param name="sourceString"></param>
        /// <returns></returns>
        public static string GetLetter(string sourceString)
        {
            Regex regex = new Regex("^[A-Za-z]+$", RegexOptions.Compiled);
            char[] stringChar = sourceString.ToCharArray();
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < stringChar.Length; i++)
            {
                if (regex.IsMatch((stringChar[i]).ToString()))
                {
                    sb.Append(stringChar[i]);
                }
            }
            return sb.ToString();
        }

 
        /// <summary>
        /// 截取字符串里的数字
        /// </summary>
        /// <param name="sourceString"></param>
        /// <returns></returns>
        public static string GetNumString(string sourceString)
        {
            Regex regex = new Regex("^-?\\d+$", RegexOptions.Compiled);
            char[] stringChar = sourceString.ToCharArray();
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < stringChar.Length; i++)
            {
                if (regex.IsMatch((stringChar[i]).ToString()))
                {
                    sb.Append(stringChar[i]);
                }
            }
            return sb.ToString();
        }

        /// <summary>
        /// 截取字符
        /// </summary>
        /// <param name="sourceString">源字符</param>
        /// <param name="beginRemovedString"></param>
        /// <param name="endRemovedString"></param>
        /// <returns></returns>
        public static string GetSubString(string sourceString, string beginRemovedString, string endRemovedString)
        {
            try
            {
                if (sourceString.IndexOf(beginRemovedString) != 0)
                    beginRemovedString = "";

                if (sourceString.LastIndexOf(endRemovedString, sourceString.Length - endRemovedString.Length) < 0)
                    endRemovedString = "";

                int startIndex = beginRemovedString.Length;
                int length = sourceString.Length - beginRemovedString.Length - endRemovedString.Length;
                if (length > 0)
                {
                    return sourceString.Substring(startIndex, length);
                }
                return sourceString;
            }
            catch
            {
                return sourceString; ;
            }
        }

        /// <summary>
        /// 按字节数取出字符串的长度
        /// </summary>
        /// <param name="str">要计算的字符串</param>
        /// <returns>字符串的字节数</returns>
        public static int GetByteCount(string str)
        {
            int intCharCount = 0;
            for (int i = 0; i < str.Length; i++)
            {
                if (System.Text.UTF8Encoding.UTF8.GetByteCount(str.Substring(i, 1)) == 3)
                {
                    intCharCount = intCharCount + 2;
                }
                else
                {
                    intCharCount = intCharCount + 1;
                }
            }
            return intCharCount;
        }

        /// <summary>
        /// 按字节数要在字符串的位置
        /// </summary>
        /// <param name="intIns">字符串的位置</param>
        /// <param name="str">要计算的字符串</param>
        /// <returns>字节的位置</returns>
        public static int GetByteIndex(int intIns, string str)
        {
            int intReIns = 0;
            if (str.Trim() == "")
            {
                return intIns;
            }
            for (int i = 0; i < str.Length; i++)
            {
                if (System.Text.UTF8Encoding.UTF8.GetByteCount(str.Substring(i, 1)) == 3)
                {
                    intReIns = intReIns + 2;
                }
                else
                {
                    intReIns = intReIns + 1;
                }
                if (intReIns >= intIns)
                {
                    intReIns = i + 1;
                    break;
                }
            }
            return intReIns;
        }

        /// <summary>
        /// 截取指定长度的字符串(包括双字节字符)
        /// </summary>
        /// <param name="str"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public static string GetSubString(string str, int length)
        {
            Regex regex = new Regex("[^\x00-\xff]", RegexOptions.Compiled);
            char[] stringChar = str.ToCharArray();
            StringBuilder sb = new StringBuilder();
            int nLength = 0;
            for (int i = 0; i < stringChar.Length; i++)
            {
                if (regex.IsMatch((stringChar[i]).ToString()))
                {
                    nLength += 2;
                }
                else
                {
                    nLength = nLength + 1;
                }

                if (nLength <= length)
                {
                    sb.Append(stringChar[i]);
                }
                else
                {
                    break;
                }
            }
            return sb.ToString();
        }
 
    }

 

posted @ 2012-08-29 16:05  暗尘掩月  阅读(1477)  评论(0编辑  收藏  举报