您的位置:首页 > Web前端 > CSS

使用正则表达式过滤html标签,属性,样式表,挂马脚本

2010-10-06 12:08 906 查看
本文介绍如何使用正则表达式过滤html标签的属性(style,class),和html标签如a,div和iframe,objectg,script.

1.使用正则表达式过滤标签样式:style,class.

比如<p style="width:100px">或<p class="myclass"></p>

可使用下面的代码:

private string FilterHtml(string element,string content)
{
string pattern = element + "\\s?=\\s?(['\"][^'\"]*?['\"]|[^'\"]\\S*)";
try
{
Regex reg = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Compiled);
content = reg.Replace(content, "");
}
catch
{ }
return content;
}

这个表达式具有普遍意义:可以过滤html的属性。如table的width等

2.使用正则表达式过滤html标签

private string FilterHtml(string element,string content)
{
string pattern = "<" + element + "[^>]*>|</" + element + ">";
try
{
Regex reg = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Compiled);
content = reg.Replace(content, "");
}
catch
{ }
return content;
}

可过滤如:<div>和</div>等。

上面的代码对提取文章摘要时很有用处。文章摘要通常先过滤html标签,在提取一段文字的。

3.使用正则表达是过滤object,script,iframe

private string FilterHtml(string element,string content)
{
string pattern = "<(?<tag>" + element + @")[^>]*>[\s\S]*</\k<tag>>";
try
{
Regex reg = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Compiled);
content = reg.Replace(content, "");
}
catch
{ }
return content;
}

在html中通过script,iframe挂马令人痛恨。使用上面的代码可以过滤这些害人虫。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: