在做網站的時候,用到了去除html標簽的問題,用正則匹配到html標簽,然后replace即可。
/// <summary>
/// C#去除HTML標簽
/// </summary>
/// <param name="html">帶有html標簽的文本</param>
/// <param name="length">截取長度</param>
/// <returns></returns>
public static string ReplaceHtmlTag(string html, int length = 0) { string strText = System.Text.RegularExpressions.Regex.Replace(html, "<[^>]+>", ""); strText = System.Text.RegularExpressions.Regex.Replace(strText, "&[^;]+;", ""); if (length > 0 && strText.Length > length) return strText.Substring(0, length); return strText; }
這個方法可以實現去除html標簽的功能。
Length參數可以根據傳入值取固定長度的值。用於生成文章摘要比較方便。