ASP.NET过滤HTML标签只保留换行与空格的方法

2019-05-23 05:52:12王旭

然后我就自己改了一下这个方法,textarea的换行是n,所以我得把这些标签重新匹配替换成<br>,这样的话从数据库中读取到页面时,就能正确的换行了,把空格替换成HTML的空格符,大功告成。
///   <summary>
///   去除HTML标记(保留br跟rn)
///   </summary>
///   <param   name="NoHTML">包括HTML的源码   </param>
///   <returns>已经去除后的文字</returns>
public static string NewNoHTML(string Htmlstring)
{
    //Htmlstring.Replace("rn", "%r%n").Replace("<br>","%br%").Replace("<br/>","%br&%").Replace("n","%n");
    //删除脚本
    Htmlstring = Regex.Replace(Htmlstring, @"<script[^>]*?>.*?</script>", "",
      RegexOptions.IgnoreCase);
    //删除HTML
    Htmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>", "",
      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(">", "");