SoFunction
Updated on 2025-03-06

C# implements a method of filtering html tags and retaining a tag

This article shows how C# implements filtering html tags, spaces between Chinese characters, tabs, and retains the a tag. Share it for your reference. The specific methods are as follows:

The following methods can be defined in public classes such as 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 = (html, stringPattern, "");
    html = (html, @"[\t\n]", "", );
    html = (html, @"[\r]", "", );
    //html = (html, @"[\t\n\r\s]","",);
    return html;
  }

Then add this method to the fields you need to filter to achieve the filtering function. I hope this article will be helpful to everyone's C# programming.