c#怎么过滤html标签并保留a标签?c#字符过滤示例

发布时间:2020-06-07编辑:脚本学堂
c#编程中过滤html标签并保留a标签是如何做到的,本文通过一个自定义函数中用正则过滤实现有选择的过滤字符,滤html标签,汉字间空格,制表符,并保留a标签。

c#字符过滤方法:
过滤html标签,汉字间空格,制表符,并保留a标签

在公共类如Common中定义方法:
 

复制代码 代码示例:
public static string ClearHtmlExceptA(string html) {
  string acceptable = "a";
  string stringPattern = @"</?(?(?=" + acceptable + @")notag|[a-zA-Z0-9]+)(?:s[a-zA-Z0-9-]+=?(?:(["",']?).*?1?)?)*s*/?>";
  html = Regex.Replace(html, stringPattern, "");
  html = Regex.Replace(html, @"[tn]", "", RegexOptions.IgnoreCase);
  html = Regex.Replace(html, @"[r]", "", RegexOptions.IgnoreCase);
  //html = Regex.Replace(html, @"[tnrs]","",RegexOptions.IgnoreCase);
  return html;
}