Home > ASP.NET 2.0 > How to remove HTML Tags From a String in c#

How to remove HTML Tags From a String in c#

Thursday, 22 May, 2008 Leave a comment Go to comments

A lot of websites allow users to input text and submit it to the site.
This could be forums, blogs, content management systems etc.
Imaging if the user writes HTML into these form fields?
It could be perfectly harmless when used for styling, but it could also be used the wrong way.
A typical scenario would be when a user enters JavaScript that does harmful things or embedding a style sheet that ruins the websites layout.
This is normally referred to as Cross-Site Scripting (XSS).
We have to mitigate that risk, and that’s when regular expression comes to the rescue.
Here is a very simple method that strips all HTML tags from a string or just the harmful tags – you decide.

The method takes two parameters: the string that needs tag removal and a boolean flag that determines if harmless tags are allowed or not.

public static string StripHtml(string html, bool allowHarmlessTags)
{
if (html == null || html == string.Empty)
return string.Empty;
if (allowHarmlessTags)
return System.Text.RegularExpressions.Regex.Replace(html, "", string.Empty);
return System.Text.RegularExpressions.Regex.Replace(html, "<[^>]*>", string.Empty);
}

You can add more harmful tags to the regular expression string if you’d like.
Enjoy.

article source

Update: OR use this function

public string Strip(string text)
{
return Regex.Replace(text, @”<(.|\n)*?>”, string.Empty);
}

article source

Advertisements
Categories: ASP.NET 2.0 Tags: ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: