如何在尊重完整單字的情況下將文字截斷為 100 個字元?

DDD
發布: 2024-10-24 06:37:02
原創
162 人瀏覽過

How to Truncate Text to 100 Characters while Respecting Full Words?

在文字截斷中尊重完整單字

在此場景中,您尋求將字串截斷為100 個字符,同時保留完整單字。與使用 substr 的直接方法不同,此方法旨在防止分詞。

要實現此目的,請考慮以下方法:

<code class="php">$content = "This is a sentence that has more than 100 characters in it, and I want to return a string of only full words that is no more than 100 characters!";

$pos = strpos($content, ' ', 100);
$truncated = substr($content, 0, $pos);</code>
登入後複製

在此程式碼中,我們首先找到第一個空格使用 strpos 在第 100 個字元之後。這可以確保我們不會打斷一個單字。隨後,我們使用 substr 將字串截斷到該位置,尊重單字邊界。

輸出將是:

"This is a sentence that has more than 100 characters in it, and I want to return a string of only"
登入後複製

以上是如何在尊重完整單字的情況下將文字截斷為 100 個字元?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!