在處理使用者輸入、爬蟲資料、RSS 摘要或郵件模板時,常需移除 HTML 標籤僅保留純文字。本文比較主流語言與正則表達式的實作方式、優缺點與注意事項。
<br>、<p>)、實體解碼(< → <)、實體編碼。String cleanText = Jsoup.parse(html).text(); // 移除所有標籤,解碼實體
String cleanWithBr = Jsoup.clean(html, Safelist.none().addTags("br", "p")); // 保留特定標籤
優點:正確處理巢狀、實體、編碼、XSS 防護;缺點:需外部依賴。
// 移除所有標籤(含屬性),保留文字
String text = html.replaceAll("(?s)<[^>]*>", "");
// 僅保留 br, p, img
String text2 = html.replaceAll("(?s)<(?!/?(br|p|img)\\b)[^>]*>", "");
警告:正則無法正確處理 <script>/<style> 內容、屬性值含 >、註釋、CDATA 等邊界情況。
function stripHtml(html, allowedTags = []) {
const doc = new DOMParser().parseFromString(html, 'text/html');
if (allowedTags.length) {
// 移除非允許標籤但保留其文字內容
doc.querySelectorAll('*').forEach(el => {
if (!allowedTags.includes(el.tagName.toLowerCase())) {
el.replaceWith(...el.childNodes);
}
});
} else {
// 全部移除
return doc.body.textContent || '';
}
return doc.body.innerHTML;
}
const stripTags = (html, allow = '') => {
const allowRe = allow ? new RegExp(`^(/)?(${allow.split(',').join('|')})$`, 'i') : null;
return html.replace(/<\/?([a-z][a-z0-9]*)\b[^>]*>/gi, (m, tag) => allowRe?.test(tag) ? m : '');
};
// 用法
stripHtml('<b>Bold</b> <br>', 'br'); // "<b>Bold</b> <br>"
// 內建函式(簡單、快速,但無法精細控制保留標籤)
$text = strip_tags($html, '<br><p><img>'); // 第二參數指定允許標籤
// 進階:HTMLPurifier(安全、可配置、移除 XSS)
require_once 'HTMLPurifier.auto.php';
$config = HTMLPurifier_Config::createDefault();
$config->set('HTML.Allowed', 'p,b,strong,i,em,br,img[src|alt],a[href|title]');
$purifier = new HTMLPurifier($config);
$clean = $purifier->purify($html);
# BeautifulSoup(推薦,健壯)
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'html.parser')
text = soup.get_text(separator=' ', strip=True)
# 保留特定標籤
for tag in soup.find_all(True):
if tag.name not in {'br', 'p'}:
tag.unwrap()
# lxml + Cleaner(高效能、可配置)
from lxml.html.clean import Cleaner
cleaner = Cleaner(remove_tags=['script', 'style'], kill_tags=['div', 'span'])
clean_html = cleaner.clean_html(html)
| 需求 | 正則(PCRE/JS/Python/Java) | 說明 |
|---|---|---|
| 移除所有標籤 | <[^>]*> 或 (?s)<.*?> | 貪婪/非貪婪匹配標籤 |
| 移除 script/style 及內容 | (?is)<(script|style).*?>.*?</\1> | 單行模式 + 忽略大小寫 |
| 僅保留 br, p, img | <(?!/?(br|p|img)\b)[^>]*> | 負向前瞻排除 |
| 移除屬性保留標籤 | <([a-z]+)\b[^>]*> → <$1> | 捕獲標籤名重組 |
DOMParser 或 innerText。記住:正則不是解析 HTML 的正確工具,僅適用於格式固定、可預測的受控輸入。