strip_tags(string $string, array|string|null $allowed_tags = null): string
<!-- -->),無法透過 allowed_tags 保留<script>、<style>)htmlspecialchars()$str = "Hello <b><i>world</i></b>!";
echo strip_tags($str); // Hello world!
echo strip_tags($str, '<b>'); // Hello <b>world</b>!
$html = '<p>段落</p><span>行內</span><div>區塊</div>';
$allow = ['p', 'span'];
echo strip_tags($html, $allow); // <p>段落</p><span>行內</span>區塊
function safeOutput($html, $allowed = []) {
$stripped = strip_tags($html, $allowed);
return htmlspecialchars($stripped, ENT_QUOTES, 'UTF-8');
}
function hasHtmlTags($str) {
return $str !== strip_tags($str);
}
// 測試
var_dump(hasHtmlTags('<p>內容')); // true
var_dump(hasHtmlTags('純文字')); // false
大量資料處理時,strip_tags() 速度尚可。若需更嚴格的 HTML 清理(如防 XSS),建議使用 HTML Purifier 等專業庫。