截斷字串時維護單字邊界
在先前的查詢中,使用者試圖使用substr() 將字串截斷為100 個字元功能。但是,此方法僅獲取前 100 個字符,在此過程中可能會破壞單字。
問題陳述
目標是將字串截斷為最多 100 個字符字符,同時確保單字保持完整。例如:
$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!" $small = truncate_string($big); echo $small; // OUTPUT: "This is a sentence that has more than 100 characters in it, and I want to return a string of only"
PHP 解決方案
以下程式碼提供了解:
<code class="php">function truncate_string($string) { $pos = strpos($string, ' ', 200); return substr($string, 0, $pos); }</code>
說明:說明:
以上是截斷字串時如何保持字邊界?的詳細內容。更多資訊請關注PHP中文網其他相關文章!