在後端處理使用者輸入或爬蟲資料時,常需移除 HTML 標籤並保留純文本。以下提供一個可直接使用的 C# 靜態方法,結合正則表達式移除標籤與 HTML 實體,並支援指定最大長度截斷。
public static string ReplaceHtmlTag(string html, int length = 0)
{
if (string.IsNullOrEmpty(html)) return string.Empty;
// 移除所有 HTML 標籤
string strText = System.Text.RegularExpressions.Regex.Replace(html, "<[^>]+>", "");
// 移除 HTML 實體(如 、< 等)
strText = System.Text.RegularExpressions.Regex.Replace(strText, "&[^;]+;", "");
// 依需求截斷長度
if (length > 0 && strText.Length > length)
return strText.Substring(0, length);
return strText;
}
string raw = "<p>Hello <b>World</b>!</p>";
string clean = ReplaceHtmlTag(raw); // "Hello World!"
string shortText = ReplaceHtmlTag(raw, 5); // "Hello"
HtmlAgilityPack 等專門解析庫。&[^;]+; 可能誤刪合法文字(如 "AT&T"),實際專案請視資料特性調整。RegexOptions.Compiled)或改用 StringBuilder 手動解析。