日期:2014-05-17 浏览次数:20735 次
public static string DelHtml(this string Htmlstring)
{
//删除脚本
Htmlstring = Regex.Replace(Htmlstring, @"<script(\s[^>]*?)?>[\s\S]*?</script>", "", RegexOptions.IgnoreCase);
//删除样式
Htmlstring = Regex.Replace(Htmlstring, @"<style>[\s\S]*?</style>", "", RegexOptions.IgnoreCase);
//删除html标签
Htmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
return Htmlstring;
}
------解决方案--------------------
你把< 和 > 等关键字符转义一下就行了.
比如 < , 转义成 < 存到数据库,读取的时候, < 就会自动转义成 < 了.
------解决方案--------------------
/// <summary>
/// HTML标签过滤
/// </summary>
/// <param name="strHtml">需要过滤的字符串</param>
/// <returns></returns>
public static string StripHTML(string strHtml)
{
string[] aryReg ={
@"<script[^>]*?>.*?</script>",
@"<(\/\s*)?!?((\w+:)?\w+)(\w+(\s*=?\s*(([""'])(\\[""'tbnr]|[^\7])*?\7|\w+)|.{0})|\s)*?(\/\s*)?>",
@"([\r\n])[\s]+",
@"&(quot|#34);",
@"&(amp|#38);",
@"&(lt|#60);",
@"&(gt|#62);",
@"&(nbsp|#160);",
@"&(iexcl|#161);",
@"&(cent|#162);",
@"&(pound|#163);",
@"&(copy|#169);",
@"&#(\d+);",
@"-->",
@"<!--.*\n"
};
string[] aryRep = {
"",
"",
"",
"\"",
"&",
"<",
">",
" ",
"\xa1",//chr(161),
"\xa2",//chr(162),
"\xa3",//chr(163),
"\xa9",//chr(169),
"",
"\r\n",
""
};
string newReg = aryReg[0];
string strOutput = strHtml;
for (int i = 0; i < aryReg.Length; i++)
{
System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(aryReg[i], System.Text.RegularExpressions.RegexOptions.IgnoreCase);
strOutput = regex.Replace(strOutput, aryRep[i]);
}
strOutput.Replace("<", "");
strOutput.Replace(">", "");
strOutput = strOutput.Replace("\r\n", "");
return strOutput;
}
------解决方案-----