處理使用者輸入或外部資料時,移除 HTML 標籤是基本的安全與清理步驟。PHP 內建 strip_tags() 功能強大,但需注意細節。
<?php
$html = '<p>Hello <strong>World</strong>!</p><br><script>alert(1)</script>';
// 移除所有標籤
echo strip_tags($html);
// 輸出: Hello World!
// 保留特定標籤
echo strip_tags($html, '<p><br>');
// 輸出: <p>Hello World!</p><br>
?>
<?php
function cleanHtml($str, $allowedTags = '<p><br><strong><em>') {
// 先統一換行標籤
$str = preg_replace('/<br\s*\/?>/i', "\n", $str);
$str = preg_replace('/<\/p>/i', "\n", $str);
$str = preg_replace('/<p[^>]*>/i', '', $str);
// 移除不允許的標籤
$str = strip_tags($str, $allowedTags);
// 清理多餘空白
$str = preg_replace('/[ \t]+/', ' ', $str);
$str = preg_replace('/\n{3,}/', "\n\n", $str);
return trim($str);
}
// 使用範例
$dirty = '<div><p>內容<script>惡意</script></p><br></div>';
echo cleanHtml($dirty);
// 輸出: <p>內容</p>\n
?>
| 情況 | 說明 |
|---|---|
| 屬性保留 | strip_tags() 不會移除標籤屬性(如 onclick、style) |
| XSS 風險 | 保留標籤時,屬性可能包含惡意代碼 |
| 損壞標籤 | 不完整標籤可能導致意外截斷 |
| 編碼問題 | 確保字串編碼一致(UTF-8) |
對於生產環境,建議使用 HTMLPurifier 庫:
require_once 'HTMLPurifier.auto.php';
$config = HTMLPurifier_Config::createDefault();
$purifier = new HTMLPurifier($config);
$clean = $purifier->purify($dirtyHtml);
正確清理 HTML 是防禦 XSS 攻擊的第一道防線。