以下提供一組實用的 PHP 正則表達式代碼,可過濾字串中的 HTML 標籤、多餘空白、換行符、註釋、DOCTYPE 宣告以及常見的危險標籤(如 <script>、<style>、<iframe> 等),並處理 HTML 實體編碼。
<?php
$str = preg_replace("/\s+/", " ", $str); // 過濾多餘換行與空白
$str = preg_replace("/<[ ]+/si", "<", $str); // 過濾 < 後的空格
$str = preg_replace("/<\!--.*?-->/si", "", $str); // 移除 HTML 註釋
$str = preg_replace("/<(\!.*?)>/si", "", $str); // 過濾 DOCTYPE
$str = preg_replace("/<(\/?html.*?)>/si", "", $str); // 過濾 html 標籤
$str = preg_replace("/<(\/?head.*?)>/si", "", $str); // 過濾 head 標籤
$str = preg_replace("/<(\/?meta.*?)>/si", "", $str); // 過濾 meta 標籤
$str = preg_replace("/<(\/?body.*?)>/si", "", $str); // 過濾 body 標籤
$str = preg_replace("/<(\/?link.*?)>/si", "", $str); // 過濾 link 標籤
$str = preg_replace("/<(\/?form.*?)>/si", "", $str); // 過濾 form 標籤
$str = preg_replace("/cookie/si", "COOKIE", $str); // 過濾 cookie 關鍵字
// 過濾 applet 標籤及其內容
$str = preg_replace("/<(applet.*?)>(.*?)<(\/applet.*?)>/si", "", $str);
$str = preg_replace("/<(\/?applet.*?)>/si", "", $str);
// 過濾 style 標籤及其內容
$str = preg_replace("/<(style.*?)>(.*?)<(\/style.*?)>/si", "", $str);
$str = preg_replace("/<(\/?style.*?)>/si", "", $str);
// 過濾 title 標籤及其內容
$str = preg_replace("/<(title.*?)>(.*?)<(\/title.*?)>/si", "", $str);
$str = preg_replace("/<(\/?title.*?)>/si", "", $str);
// 過濾 object 標籤及其內容
$str = preg_replace("/<(object.*?)>(.*?)<(\/object.*?)>/si", "", $str);
$str = preg_replace("/<(\/?objec.*?)>/si", "", $str);
// 過濾 noframes 標籤及其內容
$str = preg_replace("/<(noframes.*?)>(.*?)<(\/noframes.*?)>/si", "", $str);
$str = preg_replace("/<(\/?noframes.*?)>/si", "", $str);
// 過濾 iframe/frame 標籤及其內容
$str = preg_replace("/<(i?frame.*?)>(.*?)<(\/i?frame.*?)>/si", "", $str);
$str = preg_replace("/<(\/?i?frame.*?)>/si", "", $str);
// 過濾 script 標籤及其內容
$str = preg_replace("/<(script.*?)>(.*?)<(\/script.*?)>/si", "", $str);
$str = preg_replace("/<(\/?script.*?)>/si", "", $str);
$str = preg_replace("/javascript/si", "Javascript", $str); // 關鍵字大小寫處理
$str = preg_replace("/vbscript/si", "Vbscript", $str);
$str = preg_replace("/on([a-z]+)\s*=/si", "On\\1=", $str); // 事件屬性處理
$str = preg_replace("//si", "&#", $str); // 過濾實體編碼開頭
?>
si 修飾符:s 讓 . 匹配換行符,i 不區分大小寫。<script>...</script>)採用兩步驟:先移除標籤及內容,再移除殘留的單獨標籤。javascript:、vbscript: 等偽協議及事件屬性(onclick 等)進行關鍵字替換,降低 XSS 風險。&# 替換為 &#,防止實體編碼繞過過濾。注意:此代碼適用於簡單的內容淨化,嚴格的安全場景建議使用成熟的 HTML 凈化庫(如 HTMLPurifier)。