在資料清洗、爬蟲處理、內容安全過濾等場景,常需從字串中移除 HTML 標籤僅保留純文字。雖然正則表達式可快速實作,但HTML 結構複雜(巢狀、屬性含引號、跨行、註解、CDATA、Script/Style 內容等),純正則極難完美處理所有邊界情況。生產環境強烈建議使用成熟的 HTML 解析器。
// 簡易版:移除所有 <...> 標籤
const stripHtmlSimple = (html) => html.replace(/<[^>]*>/g, '');
// 較完整版:保留文字內容,移除 script/style 區塊
function stripHtml(html) {
const doc = new DOMParser().parseFromString(html, 'text/html');
return doc.body.textContent || '';
}
// 瀏覽器環境推薦用 DOMParser,Node.js 用 JSDOM / cheerio / htmlparser2
import re
from bs4 import BeautifulSoup # 推薦:pip install beautifulsoup4
# 正則簡易版 (不建議用於複雜 HTML)
def strip_html_regex(html):
return re.sub(r'<[^>]+>', '', html)
# 正規解法:BeautifulSoup
def strip_html_bs4(html):
soup = BeautifulSoup(html, 'html.parser')
# 移除 script/style 內容
for tag in soup(['script', 'style', 'noscript']):
tag.decompose()
return soup.get_text(separator=' ', strip=True)
// 內建函數 (最推薦)
$text = strip_tags($html); // 可選第二參數允許保留特定標籤
// 或使用 DOMDocument
$dom = new DOMDocument();
@$dom->loadHTML('' . $html); // 修正編碼
$text = $dom->textContent;
// Jsoup 庫 (推薦)
String text = Jsoup.parse(html).text();
// 正則簡易版
String text = html.replaceAll("<[^>]*>", "");
// HtmlAgilityPack (NuGet 套件)
var doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(html);
string text = doc.DocumentNode.InnerText;
// 正則簡易版
string text = Regex.Replace(html, "<[^>]*>", "");
cheerio (jQuery 風格)、jsdom (完整 DOM 實作)BeautifulSoup4 (lxml 解析器) 或 selectolax (極速)strip_tags() 或 DOMDocumentgolang.org/x/net/html 或 github.com/PuerkitoBio/goquery結論: 正則適合「已知結構固定、極簡單」的一次性腳本;任何面對不可控輸入、需穩定上線的系統,請務必使用標準 HTML 解析器。