暑假开发博雅期间遇到一个大问题:做文章摘要需要完全过滤HTML代码。
在网上找了几百个实例但一个也达不到要求。
本人于是参考PetShop源码,做了小小的改动终于实现了Html的完全过滤。
代码虽短功能却超强,运行效率也很高!
public static string ClearHtmlCode(string text)
{
text = text.Trim();
if (string.IsNullOrEmpty(text))
return string.Empty;
text = Regex.Replace(text, "[\s]{2,}", " "); //two or more spaces
text = Regex.Replace(text, "(<[b|B][r|R]/*>)+|(<[p|P](.|\n)*?>)", " "); //<br>
text = Regex.Replace(text, "(\s*&[n|N][b|B][s|S][p|P];\s*)+", " "); //
text = Regex.Replace(text, "<(.|\n)*?>", string.Empty); //any other tags
text = Regex.Replace(text, "/<\/?[^>]*>/g", string.Empty); //any other tags
text = Regex.Replace(text, "/[ | ]* /g", string.Empty); //any other tags
text = text.Replace("'", "''");
text = Regex.Replace(text, "/ [\s| | ]* /g", string.Empty);
return text;
}
发表于 @ 2007年09月09日 00:28:00|评论(loading...)|编辑