[C#] 纯文本查看 复制代码
public static string AutoCloseHtmlTags(string inputHtml)
{
var regexStartTag = new Regex(@"<(!--\u002E\u002E\u002E--|!DOCTYPE|a|abbr|" +
@"acronym|address|applet|area|article|aside|audio|b|base|basefont|bdi|bdo|big" +
@"|blockquote|body|br|button|canvas|caption|center|cite|code|col|colgroup|" +
@"command|datalist|dd|del|details|dfn|dialog|dir|div|dl|dt|em|embed|fieldset|" +
@"figcaption|figure|font|footer|form|frame|frameset|h1> to <h6|head|" +
@"header|hr|html|i|iframe|img|input|ins|kbd|keygen|label|legend|li|link|" +
@"map|mark|menu|meta|meter|nav|noframes|noscript|object|ol|optgroup|option|" +
@"output|p|param|pre|progress|q|rp|rt|ruby|s|samp|script|section|select|small|" +
@"source|span|strike|strong|style|sub|summary|sup|table|tbody|td|textarea|" +
@"tfoot|th|thead|time|title|tr|track|tt|u|ul|var|video|wbr)(\s\w+.*(\u0022|'))?>");
var startTagCollection = regexStartTag.Matches(inputHtml);
var regexCloseTag = new Regex(@"</(!--\u002E\u002E\u002E--|!DOCTYPE|a|abbr|" +
@"acronym|address|applet|area|article|aside|audio|b|base|basefont|bdi|bdo|" +
@"big|blockquote|body|br|button|canvas|caption|center|cite|code|col|colgroup|" +
@"command|datalist|dd|del|details|dfn|dialog|dir|div|dl|dt|em|embed|fieldset|" +
@"figcaption|figure|font|footer|form|frame|frameset|h1> to <h6|head|header" +
@"|hr|html|i|iframe|img|input|ins|kbd|keygen|label|legend|li|link|map|mark|menu|" +
@"meta|meter|nav|noframes|noscript|object|ol|optgroup|option|output|p|param|pre|" +
@"progress|q|rp|rt|ruby|s|samp|script|section|select|small|source|span|strike|" +
@"strong|style|sub|summary|sup|table|tbody|td|textarea|tfoot|th|thead|" +
@"time|title|tr|track|tt|u|ul|var|video|wbr)>");
var closeTagCollection = regexCloseTag.Matches(inputHtml);
var startTagList = new List<string>();
var closeTagList = new List<string>();
var resultClose = "";
foreach (Match startTag in startTagCollection)
{
startTagList.Add(startTag.Value);
}
foreach (Match closeTag in closeTagCollection)
{
closeTagList.Add(closeTag.Value);
}
startTagList.Reverse();
for (int i = 0; i < closeTagList.Count; i++)
{
if (startTagList != closeTagList)
{
int indexOfSpace = startTagList.IndexOf(
" ", System.StringComparison.Ordinal);
if (startTagList.Contains(" "))
{
startTagList.Remove(indexOfSpace);
}
startTagList = startTagList.Replace("<", "</");
resultClose += startTagList + ">";
resultClose = resultClose.Replace(">>", ">");
}
}
return inputHtml + resultClose;
}