zoukankan      html  css  js  c++  java
  • 使用正则表达式去除html标签

     不知道大家遇到这话总情况没有,从数据库读取数据,数据参杂着html标记<p>等,在显式的时候控制字符个数,这个时候就会出现页面样式串行,使用正则表达式去除html标记就不会有还这个问题.

     需要引用:System.Text.RegularExpressions

    /// <summary>
        /// 去除HTML标记
        /// </summary>
        /// <param name="NoHTML">包括HTML的源码 </param>
        /// <returns>已经去除后的文字</returns>
        public static string NoHTML(string Htmlstring)
        {
            //删除脚本
            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.Replace("<", "");
            Htmlstring.Replace(">", "");
            Htmlstring.Replace("
    ", "");
            Htmlstring = HttpContext.Current.Server.HtmlEncode(Htmlstring).Trim();
    
            return Htmlstring;
        }
    
  • 相关阅读:
    正则表达式基础知识
    成功的基本法则
    Java实现简单的格式化信函生成器
    C实现哈希表
    C实现求解给定文本中以指定字符开头和结尾的子串数量的三种算法
    Java实现求解二项式系数及代码重构
    Java 异常处理学习总结
    C实现大整数幂求模问题的两种算法
    linux 学习前言
    提高编程能力的10种方法
  • 原文地址:https://www.cnblogs.com/Chendaqian/p/3328449.html
Copyright © 2011-2022 走看看