」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何在 PHP 中根據字邊界截斷字串?

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

發佈於2024-11-07
瀏覽:532

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

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

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

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

$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;

這裡,我們先搜尋字串前 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 個字元的限制。

版本聲明 本文轉載於:1729721417如有侵犯,請洽[email protected]刪除
最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3