您所在的位置: 首页 > 开发 > .Net >

C#实现过滤HTML代码的函数

  • 摘要:本文作者使用C#编写了一个删除Page里面Code中的HTML标签的函数,供大家参考!
  • 标签:C#  过滤  HTML  代码  函数

用C#写了一段正则表达式,作用是删除Page里面Code中的HTML标签,这在做采集信息,消除其中的HTML时,很有用处。

public string checkStr(string html) 
{
System.Text.RegularExpressions.Regex regex1 =
      new System.Text.RegularExpressions.Regex(@"<script[\s\S]+</script *>", 
      System.Text.RegularExpressions.RegexOptions.IgnoreCase); 
System.Text.RegularExpressions.Regex regex2 =
      new System.Text.RegularExpressions.Regex(@" href *= *[\s\S]*script *:", 
      System.Text.RegularExpressions.RegexOptions.IgnoreCase); 
System.Text.RegularExpressions.Regex regex3 =
      new System.Text.RegularExpressions.Regex(@" no[\s\S]*=", 
      System.Text.RegularExpressions.RegexOptions.IgnoreCase); 
System.Text.RegularExpressions.Regex regex4 =
      new System.Text.RegularExpressions.Regex(@"<iframe[\s\S]+</iframe *>", 
      System.Text.RegularExpressions.RegexOptions.IgnoreCase); 
System.Text.RegularExpressions.Regex regex5 =
      new System.Text.RegularExpressions.Regex(@"<frameset[\s\S]+</frameset *>", 
      System.Text.RegularExpressions.RegexOptions.IgnoreCase); 
System.Text.RegularExpressions.Regex regex6 =
      new System.Text.RegularExpressions.Regex(@"\<img[^\>]+\>", 
      System.Text.RegularExpressions.RegexOptions.IgnoreCase);  
System.Text.RegularExpressions.Regex regex7 =
      new System.Text.RegularExpressions.Regex(@"</p>", 
      System.Text.RegularExpressions.RegexOptions.IgnoreCase); 
System.Text.RegularExpressions.Regex regex8 =
      new System.Text.RegularExpressions.Regex(@"<p>", 
      System.Text.RegularExpressions.RegexOptions.IgnoreCase); 
System.Text.RegularExpressions.Regex regex9 =
      new System.Text.RegularExpressions.Regex(@"<[^>]*>", 
      System.Text.RegularExpressions.RegexOptions.IgnoreCase); 
html = regex1.Replace(html, ""); //过滤<script></script>标记
html = regex2.Replace(html, ""); //过滤href=javascript: (<A>) 属性
html = regex3.Replace(html, " _disibledevent="); //过滤其它控件的on...事件
html = regex4.Replace(html, ""); //过滤iframe
html = regex5.Replace(html, ""); //过滤frameset
html = regex6.Replace(html, ""); //过滤frameset
html = regex7.Replace(html, ""); //过滤frameset
html = regex8.Replace(html, ""); //过滤frameset
html = regex9.Replace(html, "");
html = html.Replace(" ", "");
html = html.Replace("</strong>", "");
html = html.Replace("<strong>", "");
return html;
}

【相关文章】

【责任编辑:火凤凰 TEL:(010)68476606】

让你的代码“炫”起来——WPF开发教程
C#实用基础教程
C#技术开发指南
Scala编程语言
大型网站架构技术专家谈
 
 验证码: (点击刷新验证码)   匿名发表
  • 亮剑.NET. 图解C#开发实战

  • 作者:李新峰 付志涛 缪勇
  • 本书采用全新的图解思路,分3篇介绍使用微软C#语言开发实际应用程序的基本知识。第1篇包括10章,介绍了C#语言的基础知识,主要..
Copyright©2005-2009 51CTO.COM 版权所有