首頁  >  文章  >  後端開發  >  如何在尊重完整單字的情況下將文字截斷為 100 個字元?

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

DDD
DDD原創
2024-10-24 06:37:02164瀏覽

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中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn