zoukankan      html  css  js  c++  java
  • C#字符串去除html格式

     在使用Freetextbox等流行编辑器后获得的文字内容里会掺杂着一些html标记,有时会需要将它们处理掉,这里给出处理的方法,使用了正则表达式进行规则过滤,由于html标记都是基于<>这种格式,而且还有类似&nbsp;这样的符号,所以分了2次处理将字符串处理为无html格式的字符串。

    简易代码:

    public string NoHtml(string html)
    {
        string StrNohtml = System.Text.RegularExpressions.Regex.Replace(html, "<[^>]+>", "");
        StrNohtml = System.Text.RegularExpressions.Regex.Replace(StrNohtml, "&[^;]+;", "");
        return StrNohtml;
    }

    功能增强代码:

    public string NoHTML(string Htmlstring)  //替换HTML标记
    {
        //删除脚本
        Htmlstring = Regex.Replace(Htmlstring, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);
    
        //删除HTML
        Htmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"([
    ])[s]+", "", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"-->", "", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(quot|#34);", """, RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(nbsp|#160);", " ", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(iexcl|#161);", "xa1", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(cent|#162);", "xa2", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(pound|#163);", "xa3", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(copy|#169);", "xa9", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&#(d+);", "", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"<img[^>]*>;", "", RegexOptions.IgnoreCase);
        Htmlstring.Replace("<", "");
        Htmlstring.Replace(">", "");
        Htmlstring.Replace("
    ", "");
        Htmlstring = HttpContext.Current.Server.HtmlEncode(Htmlstring).Trim();
        return Htmlstring;
    }

    转自:http://www.cnblogs.com/wangpei/archive/2009/01/06/1370513.html

  • 相关阅读:
    SIFT 特征提取算法总结
    Bilateral Filtering(双边滤波) for SSAO(转)
    Meanshift filter实现简单图片的卡通化效果
    HBM内存介绍
    DRAM 内存介绍(三)
    Arduino教程:MPU6050的数据获取、分析与处理
    pitch yaw roll是什么
    通过经纬度坐标计算距离的方法(经纬度距离计算)ZZ
    关于已知两点经纬度求球面最短距离的公式推导
    [Math]理解卡尔曼滤波器 (Understanding Kalman Filter)
  • 原文地址:https://www.cnblogs.com/wwz-wwz/p/6365732.html
Copyright © 2011-2022 走看看