tags:

views:

372

answers:

3

I want to check the HTML tags the user is using in a rich html editor I have. I am not sure though how to do this in C#.

Should I be using Regex and what HTML tags should I be blacking listing/white listing?

A: 

Assuming the tags are entered as single string like here on StackOverflow, you'll want to split the string into individual tags first:

string[] tags = "c# html  lolcat  ".Split(
    new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

A white-/blacklist can be represented using a HashSet<T> storing the tags:

HashSet<string> blacklist = new HashSet<string>(
    StringComparer.CurrentCultureIgnoreCase) { "lolcat", "lolrus" };

Then you'd have to check if one of the tags is on the list:

bool invalid = tags.Any(blacklist.Contains);
dtb
I think the OP is talking about HTML tags/elements.
LukeH
lol yes. Hmm but I guess it could almost be the same basic idea? Everything of course is not on the same line though so not sure how to do a fast search on the stuff.
chobo2
Now that I read it again... I guess you're right. But there's no lolcat tag in HTML, so I'd have give up my example if I change my answer now. :-(
dtb
A: 

You might try the Html Agility Pack. I haven't tried it to skip tags, but it could certainly find tags.

TrueWill
A: 

A simple whitelisting approach:

string input = "<span><b>99</b> < <i>100</i></span> <!-- 99 < 100 -->";

// escape & < and >
input = input.Replace("&", "&amp;").Replace(">", "&gt;").Replace("<", "&lt;");

// unescape whitelisted tags
string output = input.Replace("&lt;b&gt;", "<b>").Replace("&lt;/b&gt;", "</b>")
                     .Replace("&lt;i&gt;", "<i>").Replace("&lt;/i&gt;", "</i>");

Output:

&lt;span&gt;<b>99</b> &lt; <i>100</i>&lt;/span&gt; &lt;!-- 99 &lt; 100 --&gt;

Rendered output:

<span>99 < 100</span> <!-- 99 < 100 -->

dtb