PHP 移除 HTML 標籤常用 strip_tags() 內建函數,若需更精細控制(如保留特定標籤、移除腳本/樣式),可使用 preg_replace 正則表達式。本文提供實用範例與安全提醒。
<?php
$html = '<script>alert(1)</script><p>Hello <b>World</b></p><style>body{color:red}</style>';
// 1. 移除 script 標籤及內容
$str = preg_replace('@<script(.*?)</script>@is', '', $html);
// 2. 移除 style 標籤及內容
$str = preg_replace('@<style(.*?)</style>@is', '', $str);
// 3. 移除所有 HTML 註釋
$str = preg_replace('@<!--(.*?)-->@is', '', $str);
// 4. 移除所有剩餘標籤(保留純文本)
$str = preg_replace('@<(.*?)>@is', '', $str);
echo $str; // 輸出: Hello World
?>
// 允許保留的標籤(如 p, br, strong)
$safe = strip_tags($html, '<p><br><strong>');
// 移除所有標籤
$plain = strip_tags($html);
htmlspecialchars($str, ENT_QUOTES, 'UTF-8') 轉義實體preg_replace 內部會快取,但可手動用 preg_match 陣列)