如何在 PHP 中根據字邊界截斷字串?

Barbara Streisand
發布: 2024-10-24 06:25:30
原創
998 人瀏覽過

How to Truncate Strings with Respect to Word Boundaries in PHP?

在PHP 中根據單字邊界縮短字串

在PHP 中, substr() 函數提供了一種截斷字串的便捷方法。但是,預設情況下,它不考慮單字邊界,這可能會導致摘錄不完整或尷尬。

為了解決這個問題,我們可以修改我們的方法來優先保留整個單字。考慮以下程式碼片段:

<code class="php">$big = "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($big, ' ', 100); // Find the first space within the first 100 characters
$small = substr($big, 0, $pos); // Truncate at the space to keep the word intact

echo $small;</code>
登入後複製

這裡,我們先搜尋字串前 100 個字元內空格的位置 (strpos($big, ' ', 100))。然後,我們使用這個位置作為截斷點 (substr($big, 0, $pos))。

這種方法確保我們始終提取完整的單詞,即使完整字串超過 100 個字元。在此範例中,輸出將為:

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

此解決方案有效保留單字邊界,同時遵守 100 個字元的限制。

以上是如何在 PHP 中根據字邊界截斷字串?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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