首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

Smarty 中使用 strip_tags 過濾 HTML 標籤並配合 truncate 截取文章內容

     編輯:PHP 綜合知識

在 PHP 開發中,strip_tags() 函數常被用於移除字串中的 HTML、XML 以及 PHP 標籤。例如:

<?php echo strip_tags("Hello <b>world!</b>"); ?>

輸出結果為:Hello world!

Smarty 模板中的應用

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 參數)。

這種組合常用於文章列表頁、摘要顯示等場景,能確保輸出純文字且長度可控。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved