萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> HTML5 教學

C# 移除 HTML 標籤:Regex 實作與長度截斷

在後端處理使用者輸入或爬蟲資料時,常需移除 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 實體(如 &nbsp;、&lt; 等)
    strText = System.Text.RegularExpressions.Regex.Replace(strText, "&[^;]+;", "");

    // 依需求截斷長度
    if (length > 0 && strText.Length > length)
        return strText.Substring(0, length);

    return strText;
}

使用範例

string raw = "<p>Hello &lt;b&gt;World&lt;/b&gt;!</p>";
string clean = ReplaceHtmlTag(raw);           // "Hello World!"
string shortText = ReplaceHtmlTag(raw, 5);    // "Hello"

注意事項

  • 正則表達式適合簡單場景;若需處理巢狀結構、腳本、樣式等複雜 HTML,建議使用 HtmlAgilityPack 等專門解析庫。
  • 移除實體的正則 &[^;]+; 可能誤刪合法文字(如 "AT&T"),實際專案請視資料特性調整。
  • 效能敏感場合可預編譯 Regex(RegexOptions.Compiled)或改用 StringBuilder 手動解析。

延伸閱讀

copyright © 萬盛學電腦網 all rights reserved