核心模式速查
| 需求 | 正則模式 | 說明 |
| 移除所有標籤 | /<[^>]*>/g | 貪婪匹配尖括號內容 |
| 移除 script 標籤及內容 | /<script[\s\S]*?<\/script>/gi | 跨行匹配,非貪婪 |
| 移除 style 標籤及內容 | /<style[\s\S]*?<\/style>/gi | 同上 |
| 移除 img 標籤 | /<img[^>]*>/gi | 自閉合標籤 |
| 保留 br、p、img,刪除其餘 | /<\/?(?!br|p|img\b)[^>]*>/gi | 負向前瞻排除 |
| 移除 table 及其所有內容 | /<table[\s\S]*?<\/table>/gi | 整表刪除 |
JavaScript 實戰封裝
function stripHtml(html, options = {}) {
const {
allowTags = [], // 保留的標籤名數組,如 ['b','i','br']
allowAttributes = {}, // 允許的屬性 { tag: ['attr1', 'attr2'] }
decodeEntities = true // 是否解碼實體
} = options;
// 1. 移除 script/style 及內容
let cleaned = html.replace(/<(script|style)[\s\S]*?<\/\1>/gi, '');
// 2. 處理標籤
if (allowTags.length) {
const tagPattern = new RegExp(`<\\/?(?!${allowTags.join('|')}\\b)[^>]*>`, 'gi');
cleaned = cleaned.replace(tagPattern, '');
} else {
cleaned = cleaned.replace(/<[^>]*>/g, '');
}
// 3. 可選:解碼實體
if (decodeEntities) {
const textarea = document.createElement('textarea');
textarea.innerHTML = cleaned;
cleaned = textarea.value;
}
return cleaned;
}
PHP 版本(原文精簡版)
<?php
$str = preg_replace('@<script(.*?)</script>@is', '', $str);
$str = preg_replace('@<iframe(.*?)</iframe>@is', '', $str);
$str = preg_replace('@<style(.*?)</style>@is', '', $str);
$str = preg_replace('@<(.*?)>@is', '', $str); // 移除所有標籤
?>
⚠️ 正則處理 HTML 的根本局限
- HTML 不是正則語言(巢狀結構、屬性值含引號/尖括號、註釋、CDATA、條件註釋…),正則無法完美解析。
- 複雜場景(惡意輸入、異常嵌套)極易繞過或誤傷。
生產環境推薦方案
- 服務端:使用成熟 HTML 解析器(PHP:
DOMDocument + HTMLPurifier;Node: cheerio/jsdom + sanitize-html;Python: bleach/lxml;Java: Jsoup)。
- 客戶端:
DOMPurify(極快、支持 Trusted Types、CSP 兼容)。
- 僅在可控、簡單、非安全關鍵場景(如編輯器預覽、日誌清洗)使用正則。