using System.Text.RegularExpressions;
public static void Main()
string scenarioA = "<p>First paragraph</p><p>second paragraph</p>";
string scenarioB = "<p>Wrapped in 'p' tags</P>";
string scenarioC = "<p><div>Wrapped in <span>'p'</span> tags</div></P>";
IHtmlString A = new HtmlString(scenarioA);
IHtmlString B = new HtmlString(scenarioB);
IHtmlString C = new HtmlString(scenarioC);
Console.WriteLine("Regex:");
Console.WriteLine(A.ReplacePTags());
Console.WriteLine(B.ReplacePTags());
Console.WriteLine(C.ReplacePTags());
Console.WriteLine("String calculation:");
Console.WriteLine(A.RemoveParagraphWrapperTags());
Console.WriteLine(B.RemoveParagraphWrapperTags());
Console.WriteLine(C.RemoveParagraphWrapperTags());
public static class HtmlStringExtensions
public static IHtmlString ReplacePTags(this IHtmlString htmlString)
string htmlText = htmlString.ToString();
htmlText = Regex.Replace(htmlText, "<p>", string.Empty, RegexOptions.IgnoreCase);
htmlText = Regex.Replace(htmlText, "</p>", string.Empty, RegexOptions.IgnoreCase);
return new HtmlString(htmlText);
public static IHtmlString RemoveParagraphWrapperTags(this IHtmlString htmlString)
string text = htmlString.ToString();
if (string.IsNullOrEmpty(text))
string trimmedText = text.Trim();
string upperText = trimmedText.ToUpper();
int paragraphIndex = upperText.IndexOf("<P>", StringComparison.Ordinal);
if (paragraphIndex != 0 || paragraphIndex != upperText.LastIndexOf("<P>", StringComparison.Ordinal) || upperText.Substring(upperText.Length - 4, 4) != "</P>")
result = new HtmlString(trimmedText.Substring(3, trimmedText.Length - 7));