萬盛學電腦網

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

ASP.NET 移除 HTML 標籤工具方法:Regex 版與 HtmlAgilityPack 版

Regex 版(簡易、效能較好、但不完美)

public static string NoHTML(string htmlString)
{
    if (string.IsNullOrEmpty(htmlString)) return string.Empty;

    // 1. 移除 script 標籤及內容
    htmlString = Regex.Replace(htmlString, @"<script[^>]*>.*?</script>", "", RegexOptions.IgnoreCase | RegexOptions.Singleline);
    
    // 2. 移除 style 標籤及內容
    htmlString = Regex.Replace(htmlString, @"<style[^>]*>.*?</style>", "", RegexOptions.IgnoreCase | RegexOptions.Singleline);
    
    // 3. 移除所有 HTML 標籤
    htmlString = Regex.Replace(htmlString, @"<[^>]+>", "", RegexOptions.IgnoreCase);
    
    // 4. 移除多餘空白行與 HTML 註解殘留
    htmlString = Regex.Replace(htmlString, @"(\r\n|\n)\s+", "\n", RegexOptions.IgnoreCase);
    htmlString = Regex.Replace(htmlString, @"-->", "", RegexOptions.IgnoreCase);
    htmlString = Regex.Replace(htmlString, @" ", " ", RegexOptions.IgnoreCase);
    
    return htmlString.Trim();
}

⚠️ Regex 版局限

  • 無法正確處理巢狀標籤、屬性值含 >、CDATA、條件式註解
  • 異常 HTML(未閉合標籤)可能導致過度/不足移除
  • 不處理實體解碼(&lt; 仍為原文)

專業級方案:HtmlAgilityPack(強烈推薦)

// NuGet: Install-Package HtmlAgilityPack
using HtmlAgilityPack;

public static string StripHtml(string html)
{
    if (string.IsNullOrEmpty(html)) return string.Empty;
    
    var doc = new HtmlDocument();
    doc.LoadHtml(html);
    
    // 移除 script/style
    foreach (var node in doc.DocumentNode.SelectNodes("//script | //style") ?? Enumerable.Empty<HtmlNode>())
        node.Remove();
    
    // 取得純文字(自動解碼實體、保留換行)
    return doc.DocumentNode.InnerText.Trim();
}

比較表

適用場景建議

  • Regex:簡單清理、效能極度敏感、輸入格式可控
  • HtmlAgilityPack:使用者輸入內容、CMS 儲存、郵件模板處理、SEO 關鍵字提取、任何生產環境
copyright © 萬盛學電腦網 all rights reserved
維度RegexHtmlAgilityPack
正確性低(邊界情況易錯)高(真實 DOM 解析)
效能高(單純字串操作)中(建構 DOM 樹)
實體解碼需自行處理自動
巢狀/異常 HTML不支援容錯處理
依賴無NuGet 套件