Skip to content

Instantly share code, notes, and snippets.

@DCCoder90
Created September 17, 2017 19:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DCCoder90/2c8d47d33be63acbea59ccc49010a0a2 to your computer and use it in GitHub Desktop.
Save DCCoder90/2c8d47d33be63acbea59ccc49010a0a2 to your computer and use it in GitHub Desktop.
Static Class to assist in stripping HTML tags from strings or Char arrays
using System;
using System.Text.RegularExpressions;
/// <summary>
/// Methods to remove HTML from strings.
/// </summary>
public static class StripTags
{
/// <summary>
/// Remove HTML from string with Regex.
/// </summary>
public static string StripTagsRegex(string source)
{
return Regex.Replace(source, "<.*?>", string.Empty);
}
/// <summary>
/// Compiled regular expression for performance.
/// </summary>
static Regex _htmlRegex = new Regex("<.*?>", RegexOptions.Compiled);
/// <summary>
/// Remove HTML from string with compiled Regex.
/// </summary>
public static string StripTagsRegexCompiled(string source)
{
return _htmlRegex.Replace(source, string.Empty);
}
/// <summary>
/// Remove HTML tags from string using char array.
/// </summary>
public static string StripTagsCharArray(string source)
{
char[] array = new char[source.Length];
int arrayIndex = 0;
bool inside = false;
for (int i = 0; i < source.Length; i++)
{
char let = source[i];
if (let == '<')
{
inside = true;
continue;
}
if (let == '>')
{
inside = false;
continue;
}
if (!inside)
{
array[arrayIndex] = let;
arrayIndex++;
}
}
return new string(array, 0, arrayIndex);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment