函數語法
strip_tags(string $string, array|string|null $allowed_tags = null): string
基本用法
<?php
$str = 'Hello <b><i>world</i></b>!';
// 移除所有標籤
echo strip_tags($str);
// 輸出:Hello world!
// 保留特定標籤 (字串格式,PHP 7.4-)
echo strip_tags($str, '<b><i>');
// 輸出:Hello <b><i>world</i></b>!
// 保留特定標籤 (陣列格式,PHP 8.0+)
echo strip_tags($str, ['b', 'i']);
// 輸出:Hello <b><i>world</i></b>!
?>
重要特性與限制
| 特性 | 說明 |
| 永遠移除 HTML 註解 | <!-- comment --> 無法透過 allow 參數保留 |
| 不驗證 HTML 結構 | 不匹配的標籤 (如 <b>text) 仍會被移除標籤部分 |
| 屬性保留 | 允許的標籤會完整保留其屬性 (含 onclick、style 等危險屬性) |
| 不處理實體編碼 | < 不會被解碼為 < |
| 位元組安全 | 支援多位元組字元 (UTF-8) |
安全性陷阱:允許標籤 ≠ 安全
<?php
$evil = '<b onclick="alert(1)">點我</b> <script>evil()</script>';
// 只允許 b 標籤
echo strip_tags($evil, '<b>');
// 輸出:<b onclick="alert(1)">點我</b>
// ⚠️ onclick 事件仍然存在!XSS 風險!
?>
安全方案:HTML Purifier / 白名單屬性過濾
<?php
// 簡易版:移除所有事件屬性與 style
function safeStripTags(string $html, array $allowedTags = ['b','i','u','p','br','span']): string {
// 1. 先用 strip_tags 保留標籤結構
$allowedStr = '<' . implode('><', $allowedTags) . '>';
$html = strip_tags($html, $allowedStr);
// 2. 移除危險屬性 (on*、style、javascript: 等)
$html = preg_replace('/\s(on\w+|style)\s*=\s*["\'][^"\']*["\']/i', '', $html);
$html = preg_replace('/\s(href|src)\s*=\s*["\']\s*javascript:/i', '', $html);
// 3. 移除 data: URI (可執行腳本)
$html = preg_replace('/\s(src|href)\s*=\s*["\']\s*data:/i', '', $html);
return $html;
}
// 使用
$safe = safeStripTags($evil, ['b', 'i', 'a', 'img']);
echo $safe; // 點我 (onclick 已移除)
?>
進階:使用 HTML Purifier (生產環境推薦)
<?php
// composer require ezyang/htmlpurifier
require 'vendor/autoload.php';
$config = HTMLPurifier_Config::createDefault();
$config->set('HTML.Allowed', 'p,b,i,u,strong,em,a[href|title],img[src|alt|width|height],ul,ol,li,br');
$config->set('URI.AllowedSchemes', ['http' => true, 'https' => true, 'mailto' => true]);
$config->set('CSS.AllowedProperties', ['font-weight', 'font-style', 'text-decoration', 'color']);
$purifier = new HTMLPurifier($config);
$cleanHtml = $purifier->purify($dirtyHtml);
?>
效能比較
| 方法 | 速度 | 安全性 | 功能完整度 |
| strip_tags() | 極快 (C 實現) | 低 (屬性殘留) | 基礎 |
| preg_replace 過濾屬性 | 快 | 中 | 中 |
| HTML Purifier | 較慢 (解析 DOM) | 高 (標準合規) | 完整 |
| DOMDocument + 白名單 | 中 | 高 | 可控 |
適用場景建議
- 純文字輸出:直接 `strip_tags($str)`,最快。
- 簡單富文本 (部落格評論):`safeStripTags()` 或 `strip_tags` + 屬性清理。
- 完整富文本編輯器輸出:必須用 HTML Purifier。
- 模板引擎輸出:使用 `{{ $var | escape }}` 自動逃逸,不要用 strip_tags。