字符处理类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Configuration;
using System.Web;
using Microsoft.VisualBasic;
using System.Security.Cryptography;
using System.Security;
using System.Text.RegularExpressions;
using System.Text;
using System.IO;
namespace DataHelp
{
/// <summary>
///*****************************
///* @Description: 字符处理类
///* @Date:2008-02-12
///* @author:chen
///***************************/
/// </summary>
public class StringHelp
{
/// <summary>
/// 检测是否不带恶意字符
/// </summary>
/// <param name="InText"></param>
/// <returns>如果参数存在不安全字符,则返回true</returns>
public static bool SqlFilter(string InText)
{
string word = "and|exec|insert|select|delete|update|master|or|truncate|declare|.";
if (InText == null)
return false;
foreach (string i in word.Split('|'))
{
if ((InText.ToLower().IndexOf(i + " ") > -1) || (InText.ToLower().IndexOf(" " + i) > -1))
{
return true;
}
}
return false;
}
/// <summary>
/// 编辑框过滤
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public static string EditRegText(string text)
{
if (!string.IsNullOrEmpty(text))
{
text = text.Replace("'", "’");
}
return text;
}
/// <summary>
/// 过滤部分不安全字符
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string RegthisStr(string str)
{
return str = str.Replace(".", "").Replace("\"", "“").Replace("'", "‘").Replace("<", "<").Replace(">", ">");
}
/// <summary>
/// 该方法用于生成指定位数的随机字符串
/// </summary>
/// <param name="VcodeNum">参数是随机数的位数</param>
/// <returns>返回一个随机数字符串</returns>
public static string RndNumStr(int VcodeNum)
{
string[] source = { "0", "1", "1", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" };
string checkCode = String.Empty;
Random random = new Random();
for (int i = 0; i < VcodeNum; i++)
{
checkCode += source[random.Next(0, source.Length)];
}
return checkCode;
}
/// <summary>
/// 该方法检测并替换用户输入的恶意字符
/// </summary>
/// <param name="text">用户输入的文字 </param>
/// <returns>返回验证后的文字 </returns>
public static string InputText(string text)
{
text = text.ToLower().Trim();
if (string.IsNullOrEmpty(text))
{
return string.Empty;
}
else
{
text = Regex.Replace(text, ".", "。");
//text = Regex.Replace(text, "=", "");
//text = Regex.Replace(text, "%", "");
text = Regex.Replace(text, "'", "’");
//text = Regex.Replace(text, "select", "");
//text = Regex.Replace(text, "insert", "");
//text = Regex.Replace(text, "delete", "");
//text = Regex.Replace(text, "or", "");
//text = Regex.Replace(text, "--", "");
//text = Regex.Replace(text, "and", "");
//text = Regex.Replace(text, "where", "");
//text = Regex.Replace(text, "update", "");
//text = Regex.Replace(text, "master", "");
//text = Regex.Replace(text, "exec", "");
//text = Regex.Replace(text, " <", "");
//text = Regex.Replace(text, ">", "");
}
return text;
}
/// <summary>
/// md5加密
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string md5(string str)
{
return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5");//.ToLower()
}
///// <summary>
///// 将数字字符串转换为float
///// </summary>
///// <param name="num"></param>
///// <returns></returns>
//public static float Inputflaot(string num)
//{
// float f = 0;
// try
// {
// f = (float)(Double.Parse(num));
// }
// catch
// {
// f = 0;
// }
// return f
//}
//public
/// <summary>
/// 检查输入的字符串是否合法,若不合法过滤则替换
/// </summary>
/// <param name="Strinput">输入的字符串</param>
/// <returns>返回一个已经处理的字符串</returns>
public static string StrConvert(string StrInput)
{
if (!string.IsNullOrEmpty(StrInput))
{
//定义需要过滤的字符
string[,] immit ={
{ "'", "’" }, { "%20", " " }, { "%24", " " },
{ "%27", " " }, { "%3a", " " }, { "%3b", " " },
{ "%3c", " " }, { ";", ";" }, { ":", ":" },
{ "%", "%" }, { "--", "--" }, { "*", "*" }, { "\\", "、、" }
};
//遍历字符串,过滤掉需要过滤的字符
for (int i = 0; i < (immit.Length / 2); i++)
{
StrInput = StrInput.Replace(immit[i, 0], immit[i, 1]);
}
}
return StrInput;
}
///<summary>
/// 避免危险字符,与字段长度处理
///</summary>
///<returns>string</returns>
public static string ClearInputString(string InputString, int MaxLength)
{
//定义一个stringBuilder字符变量---利于常变的变量
StringBuilder sb = new StringBuilder();
if ((InputString != null) && (InputString != string.Empty))
{
if (InputString.Length > MaxLength)
{
//如果长度大于最大长度时,就只截取到最大长度的内容
InputString = InputString.Substring(0, MaxLength);
}
for (int i = 0; i < InputString.Length; i++)
{
//对内容中存在的尖包括进行转换追加
//这里也可以用string.replace(objstr,objstr);
switch (InputString[i])
{
case ' ': sb.Append(""); break;
case '"': sb.Append(""); break;
case '>': sb.Append(""); break;
case '<': sb.Append(""); break;
default: sb.Append(InputString[i]); break;
}
}
sb.Replace("'", "");
}
return (sb.ToString());
}
/// <summary>
/// 截取字符串并去掉图片
/// </summary>
/// <param name="content">要处理的字符串</param>
/// <param name="length">截取长度</param>
/// <param name="tail">尾部特定字符</param>
/// <returns></returns>
public static string CutWithoutPic(string content, int length, string tail)
{
int conlength = content.Length;
int begin = 0;
int end = 0;
int endcharlen = 3;
string result = "";
begin = content.ToLower().IndexOf("<img ", 0);
if (begin == -1)
{
begin = content.ToLower().IndexOf("<input type=\"image", 0);
if (begin != -1)
{
end = content.ToLower().IndexOf("/>", begin);
if (end == -1)
{
end = content.ToLower().IndexOf(">", begin);
endcharlen = 2;
}
if (end == -1)
end = content.ToLower().IndexOf("/ >", begin);
result += content.Substring(0, begin);
result += content.Substring(end + endcharlen);
}
}
result = content;
return CutString(result, length, tail);
}
/// <summary>
/// 得到加密字符串
/// </summary>
/// <param name="strText">要加密字符串</param>
/// <param name="strEncrKey">密钥</param>
/// <returns>加密后字符串</returns>
public static string Encrypt(string strText, string strEncrKey)//加密函数
{
byte[] byKey = null;
byte[] IV = { 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF, 0x11, 0x12 };
try
{
byKey = System.Text.Encoding.UTF8.GetBytes(strEncrKey);
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] inputByteArray = Encoding.UTF8.GetBytes(strText);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
return Convert.ToBase64String(ms.ToArray());
}
catch (System.Exception error)
{
return "error:" + error.Message + "\r";
}
}
/// <summary>
/// 得到以字节为单位的字符串长度是否在min与max指定的长度之间
/// </summary>
/// <param name="str"></param>
/// <param name="min"></param>
/// <param name="max"></param>
/// <returns></returns>
public static bool CheckLenght(string str, int min, int max)
{
string dd = Regex.Replace(str, "[\u4E00-\u9FA5]", "aa");
int lenther = dd.Length;
if (lenther < min || lenther > max)
return false;
else
{
return true;
}
}
/// <summary>
/// 去除超链接标记
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string DelLink(string str)
{
if (str != null && str.Trim() != "")
return Regex.Replace(str, "(<a[^>]+>)|(</a *>)", "");
return str;
}
/// <summary>
/// 删除Html标签
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string delHtml(string str)
{
if (str != null && str.Trim() != "")
return Regex.Replace(str, "<[^>]+>", "");
return str;
}
/// <summary>
/// 删除标记
/// </summary>
/// <param name="tag"></param>
/// <param name="isContent">是否清除内容</param>
/// <returns></returns>
public static string delTag(string str, string tag, bool isContent)
{
if (tag == null || tag == "")
{
return str;
}
// "<a((.*?)("[^>]*?")(.*?))*>"
if (isContent)
{
return Regex.Replace(str, string.Format(@"<({0})[^>]*>(.*?)<\/\1>", tag), "", RegexOptions.IgnoreCase);
//return Regex.Replace(str, string.Format("<a((.*?)(\"[^>]*?\")(.*?))*>([\\s\\S]*?)<\\/\\1>", tag), "", RegexOptions.IgnoreCase);
}
return Regex.Replace(str, string.Format(@"(<{0}[^>]*(>)?)|(</{0}[^>]*>)|", tag), "", RegexOptions.IgnoreCase);
//return Regex.Replace(str, string.Format("(<{0}((.*?)(\"[^>]*?\")(.*?))*>)|(</{0}[^>]*>)", tag), "", RegexOptions.IgnoreCase);
}
/// <summary>
/// 删除字符串中的一组标记
/// </summary>
/// <param name="str">输入字符串</param>
/// <param name="tagA">标记</param>
/// <param name="isContent">是否清除内容</param>
/// <returns></returns>
public static string delTagArray(string str, string tagA, bool isContent)
{
string[] tagAa = tagA.Split(',');
foreach (string sr1 in tagAa)//遍历所有标记,删除
{
str = delTag(str, sr1, isContent);
}
return str;
}
/// <summary>
/// 删除除本标记外的所有标记
/// </summary>
/// <param name="str"></param>
/// <param name="tag"></param>
/// <returns></returns>
public static string delNotTag(string str, string tag, bool isContent)
{
return Regex.Replace(str, string.Format(@"(<(?!{0})[^>]*(>)?)|(</(?!{0})[^>]*>)|", tag), "", RegexOptions.IgnoreCase);
}
public static string delNotTag(string str, string tag)
{
//MatchCollection mc=Regex.Matches(str,
return "";
}
/// <summary>
/// 删除控制字符
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string delOption(string str)
{
return Regex.Replace(str, @"(\n)|(\t)|(\r)|(\v)|(\f)", "");
}
/// <summary>
/// 删除最处层的HTML标记
/// </summary>
/// <param name="str"></param>
/// <param name="tag"></param>
/// <returns></returns>
public static string delRLTag(string str, string tag)
{
if (tag == null || tag == "")
{
return str;
}
string zz = Regex.Match(str, string.Format("(?<=<{0}[^>]*?>)[\\s\\S]*(?=</{0}[^>]*?>)", tag), RegexOptions.IgnoreCase).Value;
if (zz == null || zz.Trim() == "")
return str;
return zz;
}
/// <summary>
/// 删除空格
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string delSpanTag(string str)
{
return Regex.Replace(str, @"[^<]\s", "");
}
/// <summary>
/// 获得权限标志
/// </summary>
/// <param name="_limitsStr">权限总字段数据</param>
/// <param name="_start">从第几个字符开始截取</param>
/// <returns></returns>
public static string GetUserLimits(string _limitsStr,int _start)
{
string _tem=string.Empty;
if (!string.IsNullOrEmpty(_limitsStr))
{
_tem=_limitsStr.Substring(_start,1);
}
return _tem;
}
/// <summary>
/// 转换权限 返回bool
/// </summary>
/// <param name="_limit"></param>
/// <returns></returns>
public static bool RunUserLimits(string _limit)
{
bool _tem;
if(_limit=="1")
{
_tem = true;
}
else
{
_tem = false;
}
return _tem;
}
/// <summary>
/// <summary>
/// 字符长度截取
/// </summary>
/// <param name="_Str">截取母串</param>
/// <param name="_length">长度</param>
/// <returns></returns>
public static string SubStr(string _Str, int _length)
{
if (_Str.Length > _length)
return _Str.Substring(0, _length - 1);
else
return _Str;
}
/// <summary>
/// 字符长度截取
/// </summary>
/// <param name="_Str">截取母串</param>
/// <param name="_length">长度</param>
/// <param name="_Dot">是否后面加点</param>
/// <returns></returns>
public static string SubStr(string _Str, int _length, bool _Dot)
{
if (_Str.Length > _length)
if (_Dot)
return _Str.Substring(0, _length - 1) + "...";
else
return _Str.Substring(0, _length - 1);
else
return _Str;
}
/// <summary>
/// 换行处理与空格的处理
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string ConvertStr(string str)
{
//字符串变量,用存储已屏蔽了相关文字的内容
string strs = "";
strs = str.Replace(Convert.ToChar(13).ToString(), "<br>");
strs = strs.Replace(Convert.ToChar(10).ToString(), " ");
return strs;
}
/// <summary>
/// 转半角
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
//public static string ToDBC(string input)
//{
// if (!string.IsNullOrEmpty(input))
// return Strings.StrConv(input, VbStrConv.Narrow, 0);
// else
// return input;
//}
/// <summary>
/// 是不是数字
/// </summary>
/// <param name="_ID"></param>
/// <returns></returns>
public static bool RntRum(string _ID)
{
if (!string.IsNullOrEmpty(_ID))
{
System.Text.RegularExpressions.Regex reg1 = new System.Text.RegularExpressions.Regex(@"^^[-]?\d+[.]?\d*$");
return reg1.IsMatch(_ID);//是否匹配数字表达式
}
else
return false;
}
/// <summary>
/// 按长度截取字符串并在尾部添加特定字符
/// </summary>
/// <param name="str">原字符串</param>
/// <param name="length">截取长度</param>
/// <param name="tail">尾部特定字符</param>
/// <returns>返回截取后含有尾部的字符串</returns>
public static string CutString(string str, int length, string tail)
{
if (string.IsNullOrEmpty(tail))
tail = "...";
if (str.Length < length)
return str;
else
return str.Substring(0, length) + tail;
}
/// <summary>
/// 时间差
/// </summary>
/// <param name="_time1">开始时间</param>
/// <param name="_time2">结束时间</param>
/// <returns></returns>
public static string CompTime(string _time1, string _time2)
{
string STime = string.Empty;
if (!string.IsNullOrEmpty(_time1))
{
if (!string.IsNullOrEmpty(_time2))//结束日期是不否有.
{
try
{
if (Convert.ToDateTime(_time2).CompareTo(Convert.ToDateTime(_time1)) > 0)//两个时间差,后者是否大于前者
{
TimeSpan ts = Convert.ToDateTime(_time2) - Convert.ToDateTime(_time1);//比较时间
int n = ts.Days;
int m = ts.Hours;
int s = ts.Minutes;
if (n > 90)
{
STime = "已过期";
}
else
{
STime = "有" + n.ToString() + "天";
}
}
else
{
STime = "系统时间错误";
}
}
catch
{
}
}
else
{
STime = "无限期";
}
}
else
{
STime = "未知时间";
}
return STime;
}
/// <summary>
/// 时间差
/// </summary>
/// <param name="_time1">开始时间</param>
/// <param name="_time2">结束时间</param>
/// <returns></returns>
public static string CompJobsTime(string StartTime, string EndTime)
{
string STime = string.Empty;
if (!string.IsNullOrEmpty(StartTime))
{
if (!string.IsNullOrEmpty(EndTime))//结束日期是不否有.
{
try
{
if (Convert.ToDateTime(EndTime).CompareTo(Convert.ToDateTime(StartTime)) > 0)//两个时间差,后者是否大于前者
{
STime = EndTime;
}
else
{
STime = "已经过期";
}
}
catch
{
}
}
else
{
STime = "长期有效";
}
}
else
{
STime = "未知时间";
}
return STime;
}
/// <summary>
/// 时间转换,获得时与分
/// </summary>
/// <param name="_Time">时间</param>
/// <returns></returns>
public static string GetHHMMTime(string _Time)
{
string Date = string.Empty;
if (!string.IsNullOrEmpty(_Time))//不为空时就进行获取里面的时与分
{
DateTime DateNow = Convert.ToDateTime(_Time);//转换为日期形
Date = DateNow.Hour.ToString() + ":" + DateNow.Minute.ToString();
}
else
{
Date = "--:--";
}
return Date;
}
/// <summary>
/// 时间转换,获得年月日
/// </summary>
/// <param name="_Time">时间</param>
/// <returns></returns>
public static string GetYMDTime(string _Time)
{
string Date = string.Empty;
if (!string.IsNullOrEmpty(_Time))//不为空时就进行获取里面的时与分
{
DateTime DateNow = Convert.ToDateTime(_Time);//转换为日期形
Date = DateNow.ToString("yyyy-MM-dd");
}
else
{
Date = "-- --";
}
return Date;
}
/// <summary>
/// 时间转换,获得年月日
/// </summary>
/// <param name="_Time">时间</param>
/// <param name="_Slipt">分割符</param>
/// <returns></returns>
public static string GetYMDTime(string _Time,string _Slipt)
{
string Date = string.Empty;
if (!string.IsNullOrEmpty(_Time))//不为空时就进行获取里面的时与分
{
DateTime DateNow = Convert.ToDateTime(_Time);//转换为日期形
Date = DateNow.Year.ToString() + _Slipt + DateNow.Month.ToString() + _Slipt + DateNow.Day.ToString();
}
else
{
Date = "--" + _Slipt + "--" + _Slipt + "--";
}
return Date;
}
/// <summary>
/// 文本突出
/// </summary>
/// <param name="_title"></param>
/// <returns></returns>
public static string ContentDisRed(string _title, string _Keys)
{
string _str = string.Empty;
if (!string.IsNullOrEmpty(_Keys))
_str = _title.Replace(_Keys, "<font color=red>" + _Keys + "</font>");
else
_str = _title;
return _str;
}
/// <summary>
/// 转换到Html
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string ToHtml(string str)
{
str = str.Replace("&", "&");
return str;
}
/// <summary>
/// 返回的数组
/// </summary>
/// <param name="_str">字符串</param>
/// <param name="_ch">分割符</param>
/// <returns></returns>
public static string[] StrSplit(string _str,char _ch)
{
string[] Dic = _str.Split(_ch);
return Dic;
}
/// <summary>
/// 判断是否为空,为空时就显示默认值
/// </summary>
/// <param name="_Str">字符串</param>
/// <param name="_Default">默认值</param>
/// <returns></returns>
public static string IfConIsEmpty(string _Str,string _Default)
{
if (string.IsNullOrEmpty(_Str))
return _Default;
else
return _Str;
}
}
}