Sanitizing text with regular expressions

Strip out HTML Tags

        public static string StripHtml(string str)
        {
            return Regex.Replace(str, "<.*?>", string.Empty);
        }

Convert string to Alphanumeric text

        public static string ToAlphanumeric(this string param)
        {
            if (string.IsNullOrWhiteSpace(param)) return string.Empty;
            return (new Regex("[^a-zA-Z0-9]")).Replace(param, "");
        }

If you want to allow spaces, modify the regex to “[^a-zA-Z0-9 ]”

Advertisements

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