在 PHP 開發中,處理使用者輸入的字串時,常需要移除其中的 HTML、XML 或 PHP 標籤,以防止跨站腳本攻擊(XSS)或單純提取純文字內容。strip_tags() 正是為此而生的內建函數,它能快速剝離字串中的標籤,並可選擇性保留特定標籤。
strip_tags(string $string, string $allow = null): string
'<b>')或多個標籤組成的字串(如 '<b><i>')。<!-- ... -->),此行為無法透過 $allow 參數改變。<a href="..."> 中的 href 會被保留若 <a> 在允許清單中。<?php
$str = "Hello <b><i>world</i></b>!";
// 1. 移除所有標籤
echo strip_tags($str);
// 輸出:Hello world!
echo '<br />';
// 2. 保留 <b> 和 <i> 標籤
echo strip_tags($str, '<b><i>');
// 輸出:Hello <b><i>world</i></b>!
?>
strip_tags($_POST['comment'])strip_tags($input, '<b><i><br>')若需更嚴格的安全過濾(如移除事件屬性 onclick、style 等),請使用 HTML Purifier 等專門函式庫,strip_tags() 僅適合簡單場景。