Чтобы удалить также пробелы между тегами, вы можете использовать следующий метод: комбинация между регулярным выражением и обрезкой для пробелов в начале и конце ввода html:
public static string StripHtml(string inputHTML)
{
const string HTML_MARKUP_REGEX_PATTERN = @"<[^>]+>\s+(?=<)|<[^>]+>";
inputHTML = WebUtility.HtmlDecode(inputHTML).Trim();
string noHTML = Regex.Replace(inputHTML, HTML_MARKUP_REGEX_PATTERN, string.Empty);
return noHTML;
}
Итак, для следующего input:
<p> <strong> <em><span style="text-decoration:underline;background-color:#cc6600;"></span><span style="text-decoration:underline;background-color:#cc6600;color:#663333;"><del> test text </del></span></em></strong></p><p><strong><span style="background-color:#999900;"> test 1 </span></strong></p><p><strong><em><span style="background-color:#333366;"> test 2 </span></em></strong></p><p><strong><em><span style="text-decoration:underline;background-color:#006600;"> test 3 </span></em></strong></p>
Выход будет только текстом без пробелов между тегами html или пробелом до или после html: «test text test 1 test 2 test 3».
Please обратите внимание, что пробелы до test text
взяты из <del> test text </del>
html, а пробел после test 3
- из <em><span style="text-decoration:underline;background-color:#006600;"> test 3 </span></em></strong></p>
html.