在 PHP 開發中,strip_tags() 函數常被用於移除字串中的 HTML、XML 以及 PHP 標籤。例如:
<?php echo strip_tags("Hello <b>world!</b>"); ?>
輸出結果為:Hello world!
Smarty 模板引擎內建了 strip_tags 修飾符,可直接在模板中剝離變數內的所有 HTML 標籤(包含 < > 之間的任何內容)。
index.php:
<?php
$smarty = new Smarty;
$smarty->assign('articleTitle', 'Blind Woman Gets <span style="font-family: helvetica;">New Kidney</span> from Dad she Hasn\'t Seen in <strong>years</strong>.');
$smarty->display('index.tpl');
?>
index.tpl:
{$articleTitle}
{$articleTitle|strip_tags}
輸出結果:
Blind Woman Gets <span style="font-family: helvetica;">New Kidney</span> from Dad she Hasn't Seen in <strong>years</strong>.
Blind Woman Gets New Kidney from Dad she Hasn't Seen in years.
若需在去除標籤後進一步截取字數,可搭配 truncate 修飾符使用:
{$article.content|strip_tags|truncate:35:"…":true}
上述語法會先移除 HTML 標籤,再截取前 35 個字元,超出部分以「…」表示,並保留完整單字(true 參數)。
這種組合常用於文章列表頁、摘要顯示等場景,能確保輸出純文字且長度可控。