C#去掉HTML标记
2024-10-14 08:56:06
该方法亲测可行,下面直接粘贴代码.
public string RemoveHTMLTags(string htmlStream)
{
if (htmlStream == null)
{
throw new Exception("Your input html stream is null!");
return null;
}
/*
* 最好把所有的特殊HTML标记都找出来,然后把与其相对应的Unicode字符一起影射到Hash表内,最后一起都替换掉
*/
//先单独测试,成功后,再把所有模式合并
//注:这两个必须单独处理
//去掉嵌套了HTML标记的JavaScript:(<script)[\\s\\S]*(</script>)
//去掉css标记:(<style)[\\s\\S]*(</style>)
//去掉css标记:\\..*\\{[\\s\\S]*\\}
htmlStream = Regex.Replace(htmlStream, "(<script)[\\s\\S]*?(</script>)|(<style)[\\s\\S]*?(</style>)", " ", RegexOptions.IgnoreCase);
//htmlStream = RemoveTag(htmlStream, "script");
//htmlStream = RemoveTag(htmlStream, "style");
//去掉普通HTML标记:<[^>]+>
//替换空格: |&|­| |
htmlStream = Regex.Replace(htmlStream, "<[^>]+>| |&|­| ||•|<|>", " ", RegexOptions.IgnoreCase);
//htmlStream = RemoveTag(htmlStream);
//替换左尖括号
//htmlStream = Regex.Replace(htmlStream, "<", "<");
//替换右尖括号
//htmlStream = Regex.Replace(htmlStream, ">", ">");
//替换空行
//htmlStream = Regex.Replace(htmlStream, "[\n|\r|\t]", " ");//[\n|\r][\t*| *]*[\n|\r]
htmlStream = Regex.Replace(htmlStream, "(\r\n[\r|\n|\t| ]*\r\n)|(\n[\r|\n|\t| ]*\n)", "\r\n");
htmlStream = Regex.Replace(htmlStream, "[\t| ]{1,}", " ");
return htmlStream.Trim();
}
最新文章
- Linux学习心得之 Linux下ant安装与使用
- CI框架如何在主目录application目录之外使用uploadify上传插件和bootstrap前端框架:
- Resolving SQL Server Disk IO bottlenecks
- 关于AFNetworking菊花转圈圈的问题
- XAML: x:DeferLoadStrategy, x:Null
- [转]关于安装hadoop中出现的的 $HADOOP_HOME is deprecated 的解决方法
- 窗体移动API
- 使用Beanstalkd实现队列
- HDU 1247 Hat’s Words
- spring读取properties文件
- embedded dylibs/frameworks are only supported on iOS 8.0 and later 错误解决
- IPC之消息队列详解与使用
- Asp.Net 网站访问人数及在线人数
- 【LeetCode】89. Gray Code
- [Sdoi2017]相关分析 [线段树]
- MySQL InnoDB 修改表列Online DDL
- selenium-webdriver的二次封装(十)
- [模板] BSGS/扩展BSGS
- python控制流
- day0320 时间模块 collection模块