Strip all HTML tags from string
This is something we need very often. Either for security reasons or just because of some business rules. I will share a small code snippet with you as an extension method to string type so you can take advantages of using Regular Expressions to remove HTML tags from any user input.
public static string StripHtml(this string value)
{
if (string.IsNullOrEmpty(value))
{
return string.Empty;
}
value = Regex.Replace(value, @"<(.|\n)*?>", string.Empty, RegexOptions.Multiline | RegexOptions.IgnoreCase);
return value;
}
And this is how you need to use it:
string var = txUserInput.Text; var = var.StringHtml();
| Print article | This entry was posted by Coskun SUNALI on 9 Nov 2008 - Sun at 11:15, and is filed under General. Follow any responses to this post through RSS 2.0. You can leave a response or trackback from your own site. |
about 1 year ago
Extension-method:
public static StripMarkup(this string s)
{
if (string.IsNullOrEmpty(s))
{
return string.Empty;
}
s = Regex.Replace(s, @”", string.Empty, RegexOptions.Multiline | RegexOptions.IgnoreCase);
return s;
}
you can now use:
var myvar = txtUserInput.Text.StripMarkup();
about 1 year ago
apparently it stripped out the regex.. lol.. and I forgot to put in the return-type “string” for the method :) – you need to fix that yourself.
about 1 year ago
This worked great. Thanks for this bit of code.