C# – How to filter all HTML tags except a certain whitelist

chtmlregexvb.net

This is for .NET. IgnoreCase is set and MultiLine is NOT set.

Usually I'm decent at regex, maybe I'm running low on caffeine…

Users are allowed to enter HTML-encoded entities (<lt;, <amp;, etc.), and to use the following HTML tags:

u, i, b, h3, h4, br, a, img

Self-closing <br/> and <img/> are allowed, with or without the extra space, but are not required.

I want to:

  1. Strip all starting and ending HTML tags other than those listed above.
  2. Remove attributes from the remaining tags, except anchors can have an href.

My search pattern (replaced with an empty string) so far:

<(?!i|b|h3|h4|a|img|/i|/b|/h3|/h4|/a|/img)[^>]+>

This seems to be stripping all but the start and end tags I want, but there are three problems:

  1. Having to include the end tag version of each allowed tag is ugly.
  2. The attributes survive. Can this happen in a single replacement?
  3. Tags starting with the allowed tag names slip through. E.g., "<abbrev>" and "<iframe>".

The following suggested pattern does not strip out tags that have no attributes.

</?(?!i|b|h3|h4|a|img)\b[^>]*>

As mentioned below, ">" is legal in an attribute value, but it's safe to say I won't support that. Also, there will be no CDATA blocks, etc. to worry about. Just a little HTML.

Loophole's answer is the best one so far, thanks! Here's his pattern (hoping the PRE works better for me):

static string SanitizeHtml(string html)
{
    string acceptable = "script|link|title";
    string stringPattern = @"</?(?(?=" + acceptable + @")notag|[a-zA-Z0-9]+)(?:\s[a-zA-Z0-9\-]+=?(?:([""']?).*?\1?)?)*\s*/?>";
    return Regex.Replace(html, stringPattern, "sausage");
}

Some small tweaks I think could still be made to this answer:

  1. I think this could be modified to capture simple HTML comments (those that do not themselves contain tags) by adding "!–" to the "acceptable" variable and making a small change to the end of the expression to allow for an optional trailing "\s–".

  2. I think this would break if there are multiple whitespace characters between attributes (example: heavily-formatted HTML with line breaks and tabs between attributes).

Edit 2009-07-23: Here's the final solution I went with (in VB.NET):

 Dim AcceptableTags As String = "i|b|u|sup|sub|ol|ul|li|br|h2|h3|h4|h5|span|div|p|a|img|blockquote"
 Dim WhiteListPattern As String = "</?(?(?=" & AcceptableTags & _
      ")notag|[a-zA-Z0-9]+)(?:\s[a-zA-Z0-9\-]+=?(?:([""']?).*?\1?)?)*\s*/?>"
 html = Regex.Replace(html, WhiteListPattern, "", RegExOptions.Compiled)

The caveat is that the HREF attribute of A tags still gets scrubbed, which is not ideal.

Best Answer

Here's a function I wrote for this task:

static string SanitizeHtml(string html)
{
    string acceptable = "script|link|title";
    string stringPattern = @"</?(?(?=" + acceptable + @")notag|[a-zA-Z0-9]+)(?:\s[a-zA-Z0-9\-]+=?(?:(["",']?).*?\1?)?)*\s*/?>";
    return Regex.Replace(html, stringPattern, "sausage");
}

Edit: For some reason I posted a correction to my previous answer as a separate answer, so I am consolidating them here.

I will explain the regex a bit, because it is a little long.

The first part matches an open bracket and 0 or 1 slashes (in case it's a close tag).

Next you see an if-then construct with a look ahead. (?(?=SomeTag)then|else) I am checking to see if the next part of the string is one of the acceptable tags. You can see that I concatenate the regex string with the acceptable variable, which is the acceptable tag names seperated by a verticle bar so that any of the terms will match. If it is a match, you can see I put in the word "notag" because no tag would match that and if it is acceptable I want to leave it alone. Otherwise I move on to the else part, where i match any tag name [a-z,A-Z,0-9]+

Next, I want to match 0 or more attributes, which I assume are in the form attribute="value". so now I group this part representing an attribute but I use the ?: to prevent this group from being captured for speed: (?:\s[a-z,A-Z,0-9,-]+=?(?:(["",']?).?\1?))

Here I begin with the whitespace character that would be between the tag and attribute names, then match an attribute name: [a-z,A-Z,0-9,-]+

next I match an equals sign, and then either quote. I group the quote so it will be captured, and I can do a backreference later \1 to match the same type of quote. In between these two quotes, you can see I use the period to match anything, however I use the lazy version *? instead of the greedy version * so that it will only match up to the next quote that would end this value.

next we put a * after closing the groups with parenthesis so that it will match multiple attirbute/value combinations (or none). Last we match some whitespace with \s, and 0 or 1 ending slashes in the tag for xml style self closing tags.

You can see I'm replacing the tags with sausage, because I'm hungry, but you could replace them with empty string too to just clear them out.