strip_tags() 的第二參數 $allowable_tags 支援保留多個標籤,只需以空格分隔。但若需求是「移除特定標籤而保留其餘」,則需自定義黑名單函數。本文完整演示兩種模式。
string strip_tags ( string $str [, string $allowable_tags ] )
<?php $str = "<p>我來自<b><a href='https://example.com'>範例網站</a></b></p>"; // 1. 不保留任何標籤 echo strip_tags($str); // 輸出:我來自範例網站 // 2. 僅保留 <a> echo strip_tags($str, "<a>"); // 輸出:我來自<a href='https://example.com'>範例網站</a> // 3. 保留 <p> 和 <b>(空格分隔) echo strip_tags($str, "<p> <b>"); // 輸出:<p>我來自<b>範例網站</b></p> ?>
注意: $allowable_tags 中標籤必須完整寫出(含尖括號),多個標籤以空格分隔,不支援正則或通配符。
場景:保留大部分標籤,僅移除 <script>、<iframe>、<style> 等危險標籤。strip_tags() 無法直接實現,需自定義函數:
<?php
function strip_selected_tags($text, $tags = array()) {
$args = func_get_args();
$text = array_shift($args);
$tags = func_num_args() > 2 ? array_diff($args, array($text)) : (array) $tags;
foreach ($tags as $tag) {
// 移除成對標籤並保留內容
if (preg_match_all('/<'.$tag.'[^>]*>([^<]*)<\/'.$tag.'>/iu', $text, $found)) {
$text = str_replace($found[0], $found[1], $text);
}
}
// 移除殘留的單標籤/屬性
return preg_replace('/(<('.join('|', $tags). ')( | |.)*>)/iu', '', $text);
}
// 測試
$str = "<p>正常段落</p><script>alert(1)</script><b>加粗</b>";
echo strip_selected_tags($str, array('script', 'iframe'));
// 輸出:<p>正常段落</p>alert(1)<b>加粗</b>
?>
strip_selected_tags($str, 'script', 'iframe')<tag>content</tag>,用 content 替換整個標籤對<br/>)或帶屬性的開啟標籤| 場景 | 推薦方案 |
|---|---|
| 只需保留少數安全標籤 | strip_tags($str, '<p> <b> <a>') |
| 需移除少數危險標籤 | 自定義 strip_selected_tags() 黑名單函數 |
| 複雜 HTML 淨化(防 XSS) | 使用 HTMLPurifier 庫,業界標準方案 |
strip_tags() 不處理屬性:保留的 <a href="javascript:..."> 仍可執行 JS選對模式(白名單/黑名單),配合 HTMLPurifier 做最終防線,才能兼顧開發效率與安全性。