在後端處理使用者輸入、RSS 解析、郵件樣板等情境時,常需「去除 HTML 標籤」只保留純文字。本文提供 C# 完整實作,涵蓋 Regex 移除標籤、HTML 實體解碼、Script/Style 區塊清理、多餘空白折疊等實務細節。
<script>、<style> 等不可见區塊<...>,保留內文<→<、 →空格)HtmlEncodeusing System;
using System.Text.RegularExpressions;
using System.Web;
public static class HtmlSanitizer
{
///
/// 移除 HTML 標籤並解碼實體,回傳純文字
///
public static string StripTags(string html)
{
if (string.IsNullOrWhiteSpace(html)) return string.Empty;
// 1. 移除 script / style 區塊(含跨行)
var noScripts = Regex.Replace(html, @"<script[^>]*>.*?</script>", "", RegexOptions.IgnoreCase | RegexOptions.Singleline);
noScripts = Regex.Replace(noScripts, @"<style[^>]*>.*?</style>", "", RegexOptions.IgnoreCase | RegexOptions.Singleline);
// 2. 移除 HTML 註解
noScripts = Regex.Replace(noScripts, @"<!--.*?-->", "", RegexOptions.Singleline);
// 3. 移除所有標籤
var noTags = Regex.Replace(noScripts, @"<[^>]+>", "");
// 4. 解碼常見 HTML 實體
noTags = HttpUtility.HtmlDecode(noTags);
// 5. 折疊多餘空白字元(保留單一空格/換行)
noTags = Regex.Replace(noTags, @"[\r\n\t]+", "\n"); // 統一換行
noTags = Regex.Replace(noTags, @"[ \u00A0]{2,}", " "); // 多空格→單空格
noTags = Regex.Replace(noTags, @"\n{3,}", "\n\n"); // 多換行→雙換行
return noTags.Trim();
}
}
| Pattern | 用途 | Flags |
|---|---|---|
<script[^>]*>.*?</script> | 刪除 script 區塊 | IgnoreCase + Singleline |
<style[^>]*>.*?</style> | 刪除 style 區塊 | 同上 |
<!--.*?--> | 刪除註解 | Singleline |
<[^>]+> | 刪除所有標籤 | 預設 |