StringHelper

using System;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Data;
using System.Collections;

namespace XXXX.Common
{
    /// 
    /// 字符串操作方法
    /// 
    public class StringHelper
    {
        #region SQL 特殊字符过滤,防SQL注入
        /// 
        /// SQL 特殊字符过滤,防SQL注入
        /// 
        /// 检查的SQL语句
        /// 
        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 替换标记内的内容
        /// 
        /// 替换标记内的内容
        /// 
        /// 开始标记
        /// 结束标记
        /// 原始内容
        /// 替换内容
        /// 
        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;
        }

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

        #region 清除脚本等内容
        /// 
        /// 清除所有HTML标记
        /// 
        /// 
        /// 
        public static string ClearHtml( string contents )
        {
            contents = Regex.Replace(contents, "<(object|script)(.*?)>((.|\n)*?)", " ", RegexOptions.IgnoreCase);
            contents = Regex.Replace(contents, "", " ", 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;
        }

        /// 
        /// 清除所有HTML标记
        /// 
        /// 
        /// 
        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 代码过滤
        /// 
        /// 代码解释功能,目的是为了防止一些人恶意的提交一些代码,影响系统的安全使用,通过字符转换的方法,防止这种现象的发生
        /// 
        /// 要转换的数据字符串
        /// 要过滤掉的单个格式
        /// 替换后的字符
        /// 
        /// DecodeFilter 方法是为了防止提交恶意代码而使用的,可以过滤 Script,Table,Class,Style,XML,NAMESPACE,MARQUEE,FONT,Object等标签的内容
        /// 
        /// 
        /// 以下示例演示了如何使用 DecodeFilter 过滤包含Script脚本的内容:
/// /// /// str = DecodeFilter(str,"SCRIPT"); /// ///
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, "]*>", ""); r = new Regex(@"]*>", 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, "]*>", ""); str = Regex.Replace(str, "]*>", ""); str = Regex.Replace(str, "]*>", ""); str = Regex.Replace(str, "]*>", ""); str = Regex.Replace(str, "]*>", ""); 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": //不允许使用 这种格式 str = Regex.Replace(str, @"<\/?[a-z]+:[^>]*>", ""); break; case "FONT": //不允许使用 font 标签,不建议使用 str = Regex.Replace(str, "]*>", ""); break; case "MARQUEE": //不允许使用 marquee 标签,也就没有移动滚动的特殊 str = Regex.Replace(str, "]*>", ""); break; case "OBJECT": //不允许 object, param, embed 标签,不能嵌入对象 str = Regex.Replace(str, "]*>", ""); str = Regex.Replace(str, "]*>", ""); str = Regex.Replace(str, "]*>", ""); break; } return str; } #endregion #region 字符加密 /// /// SHA1 /// /// /// public static string Entrypt( string str ) { return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "sha1"); } /// /// MD5 /// /// /// public static string EntryptMD5( string str ) { return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "md5"); } /// /// Base64编码 /// /// /// public static string GetBase64Encode(string str) { return Convert.ToBase64String(System.Text.Encoding.Default.GetBytes(str)); } /// /// Base64解码 /// /// /// public static string GetBase64Decode(string str) { return Encoding.Default.GetString(Convert.FromBase64String(str)); } #endregion #region 截取字符 /// /// 截取字符 /// /// 需要截取的字符 /// 截取长度 /// 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 生成一个随机不重复的字符串 /// /// 生成一个随机不重复的字符串,用于文件命名 /// /// 返回 public static string RadomFileName() { return Entrypt(DateTime.Now.ToUniversalTime().ToString().Replace("-", "").Replace(":", "").Replace(" ", "") + GetRandomNext(5).ToString()); } #endregion #region 随机数 /// /// 生成小于10位长度的随机数 /// /// /// 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地址最后一位用*号代替" /// /// 隐藏IP地址最后一位用*号代替 /// /// IP地址:192.168.34.23 /// public static string HidenLastIP(string ip) { if (ip.Trim() != string.Empty) { return ip.Substring(0, ip.LastIndexOf(".")) + ".*"; } else return string.Empty; } #endregion #region "按字符串位数补0" /// /// 按字符串位数补0 /// /// 字符串 /// 字符长度 /// 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 "正式表达式验证" /// /// 正式表达式验证 /// /// 验证字符 /// 正式表达式 /// 符合true不符合false public static bool CheckRegex(string content, string regex) { Regex match = new Regex(regex, RegexOptions.Compiled); return match.Match(content).Success; } #endregion /// /// 从字符串中的尾部删除指定的字符串 /// /// 源内容 /// 要移除的字符 /// 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; } } /// /// 获取拆分符右边的字符串 /// /// /// /// 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; } /// /// 获取拆分符左边的字符串 /// /// /// /// 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; } /// /// 删除不可见字符 /// /// /// 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(); } /// /// 获取数组元素的合并字符串 /// /// /// public static string GetArrayString(string[] stringArray) { string totalString = null; for (int i = 0; i < stringArray.Length; i++) { totalString = totalString + stringArray[i]; } return totalString; } /// /// 获取某一字符串在字符串数组中出现的次数 /// /// /// /// 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; } /// /// 获取某一字符串在字符串中出现的次数 /// /// 原字符串 /// 匹配字符串 /// /// 匹配字符串数量 /// 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; } /// /// 截取从startString开始到原字符串结尾的所有字符 /// /// /// /// 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 ""; } } /// /// 截取字符串里面的字母 /// /// /// 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(); } /// /// 截取字符串里的数字 /// /// /// 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(); } /// /// 截取字符 /// /// 源字符 /// /// /// 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; ; } } /// /// 按字节数取出字符串的长度 /// /// 要计算的字符串 /// 字符串的字节数 public static int GetByteCount(string strTmp) { int intCharCount = 0; for (int i = 0; i < strTmp.Length; i++) { if (System.Text.UTF8Encoding.UTF8.GetByteCount(strTmp.Substring(i, 1)) == 3) { intCharCount = intCharCount + 2; } else { intCharCount = intCharCount + 1; } } return intCharCount; } /// /// 按字节数要在字符串的位置 /// /// 字符串的位置 /// 要计算的字符串 /// 字节的位置 public static int GetByteIndex(int intIns, string strTmp) { int intReIns = 0; if (strTmp.Trim() == "") { return intIns; } for (int i = 0; i < strTmp.Length; i++) { if (System.Text.UTF8Encoding.UTF8.GetByteCount(strTmp.Substring(i, 1)) == 3) { intReIns = intReIns + 2; } else { intReIns = intReIns + 1; } if (intReIns >= intIns) { intReIns = i + 1; break; } } return intReIns; } /// /// 获取字符串的实际长度,全解字符算两个长度 /// /// 要统计长度的字符串 /// 字符串长度 public static int GetLength(string oString) { byte[] strArray = System.Text.Encoding.Default.GetBytes(oString); int res = strArray.Length; return res; } /// /// 截取指定长度的字符串(包括双字节字符) /// /// /// /// 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(); } } }

你可能感兴趣的:(asp.net,C#,.net)