首頁  >  文章  >  後端開發  >  截斷字串時如何保持字邊界?

截斷字串時如何保持字邊界?

Mary-Kate Olsen
Mary-Kate Olsen原創
2024-10-24 06:32:02922瀏覽

How to Maintain Word Boundaries When Truncating Strings?

截斷字串時維護單字邊界

在先前的查詢中,使用者試圖使用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>

說明:說明:

  • strpos() 函數在字串的前200 個字元內搜尋下一個空格字元。這確保我們不會截斷超過前 100 個字元。
  • substr() 函數傳回從字串開頭到指定位置的子字串,即前 200 個字元中第一個空格的位置字元。

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

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