Created
November 10, 2016 16:40
-
-
Save mganss/00bec2c2245c0ef86d9c82d6211def7b to your computer and use it in GitHub Desktop.
Encode non-HTML before HTML sanitization
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
static Regex HtmlRegex = new Regex(@"</?([a-z]+[1-6]?)", RegexOptions.IgnoreCase); | |
static HashSet<string> HtmlTags = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "a", "abbr", "acronym", "address", "applet", "area", "article", "aside", "audio", "b", "base", "bdi", "bdo", "big", "blockquote", "body", "br", "button", "canvas", "caption", "center", "cite", "code", "col", "colgroup", "command", "datalist", "dd", "del", "details", "dfn", "dir", "div", "dl", "dt", "em", "embed", "fieldset", "figcaption", "figure", "font", "footer", "form", "frame", "h1", "h2", "h3", "h4", "h5", "h6", "head", "header", "hgroup", "hr", "html", "i", "iframe", "img", "input", "ins", "isindex", "kbd", "keygen", "label", "legend", "li", "link", "map", "mark", "menu", "meta", "meter", "nav", "noscript", "object", "ol", "optgroup", "option", "output", "p", "param", "pre", "progress", "q", "rp", "rt", "ruby", "s", "samp", "script", "section", "select", "small", "source", "span", "strike", "strong", "style", "sub", "summary", "sup", "table", "tbody", "td", "textarea", "tfoot", "th", "thead", "time", "title", "tr", "track", "tt", "u", "ul", "var", "video", "wbr" }; | |
private string Sanitize(string text) | |
{ | |
text = HtmlRegex.Replace(text, m => | |
{ | |
var tagName = m.Groups[1].Value; | |
if (!HtmlTags.Contains(tagName)) | |
return "<" + m.Value.Substring(1); | |
return m.Value; | |
}); | |
var sanitized = Sanitizer.Sanitize(text).Replace("\n", "<br>"); | |
return sanitized; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment