PHP 提供 strip_tags() 快速移除字串中的 HTML/PHP 標籤,是表單輸入清洗、內容摘要生成的常用工具。
strip_tags(string $string, array|string|null $allowed_tags = null): string
$string:輸入字串$allowed_tags:選填,允許保留的標籤(字串或陣列,PHP 8.0+ 支援陣列)$html = '<div><p>內容</p><script>alert(1)</script><b>粗體</b></div>';
// 1. 移除所有標籤
echo strip_tags($html);
// 輸出: 內容alert(1)粗體
// 2. 保留特定標籤(字串格式)
echo strip_tags($html, '<p><b>');
// 輸出: <p>內容</p>alert(1)<b>粗體</b>
// 3. 保留特定標籤(陣列格式,PHP 8.0+)
echo strip_tags($html, ['p', 'b']);
// 輸出同上
// 4. 處理換行標籤
$text = "第一行<br />\n第二行<br>";
echo strip_tags($text, '<br>');
// 輸出保留 br 標籤
function cleanHtml($html, $allowedTags = ['p', 'br', 'b', 'strong', 'i', 'em', 'ul', 'ol', 'li']) {
// 1. 統一換行標籤
$html = str_replace(['<br>', '<br/>'], '<br />', $html);
// 2. 移除不允許標籤
$allowed = implode('', array_map(fn($t) => "<$t>", $allowedTags));
$clean = strip_tags($html, $allowed);
// 3. 實體編碼防 XSS(若輸出至 HTML)
// $clean = htmlspecialchars($clean, ENT_QUOTES, 'UTF-8');
// 4. 修剪多餘空白
$clean = preg_replace('/\s+/', ' ', $clean);
return trim($clean);
}
// 使用
$dirty = '<div onload="alert(1)"><p>安全</p><script>惡意</script></div>';
echo cleanHtml($dirty); // <p>安全</p>惡意
strip_tags 不解析屬性,<img src=x onerror=alert(1)> 會保留危險屬性<script> 不會被處理<div> 但移除 <p> 可能產生無效 HTMLcomposer require ezyang/htmlpurifier
$config = HTMLPurifier_Config::createDefault();
$config->set('HTML.AllowedElements', ['p', 'b', 'strong', 'i', 'em', 'ul', 'ol', 'li', 'br', 'a']);
$config->set('HTML.AllowedAttributes', ['a.href', 'a.title', '*.class', '*.id']);
$purifier = new HTMLPurifier($config);
$clean = $purifier->purify($dirtyHtml);
function sanitizeHtml($html, $allowedTags = ['p', 'b', 'br']) {
$dom = new DOMDocument();
$dom->loadHTML('<meta charset="utf-8">' . $html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$xpath = new DOMXPath($dom);
foreach ($xpath->query('//*') as $node) {
if (!in_array($node->tagName, $allowedTags)) {
// 移除節點但保留子節點
while ($node->childNodes->length) {
$node->parentNode->insertBefore($node->childNodes->item(0), $node);
}
$node->parentNode->removeChild($node);
} else {
// 清理屬性
foreach ($node->attributes as $attr) {
if (!in_array($attr->name, ['href', 'title', 'class', 'id'])) {
$node->removeAttribute($attr->name);
}
}
}
}
return $dom->saveHTML();
}
strip_tags() 足夠htmlspecialchars() 或模板引擎自動轉義安全無小事,選對工具守住第一道防線。