萬盛學電腦網

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

正則表達式匹配/移除 HTML 標籤:常用模式、陷阱與最佳實踐

核心模式速查

需求正則模式說明
移除所有標籤/<[^>]*>/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、條件註釋…),正則無法完美解析。
  • 複雜場景(惡意輸入、異常嵌套)極易繞過或誤傷。

生產環境推薦方案

  1. 服務端:使用成熟 HTML 解析器(PHP: DOMDocument + HTMLPurifier;Node: cheerio/jsdom + sanitize-html;Python: bleach/lxml;Java: Jsoup)。
  2. 客戶端:DOMPurify(極快、支持 Trusted Types、CSP 兼容)。
  3. 僅在可控、簡單、非安全關鍵場景(如編輯器預覽、日誌清洗)使用正則。
copyright © 萬盛學電腦網 all rights reserved