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

Mary-Kate Olsen
發布: 2024-10-24 06:32:02
原創
920 人瀏覽過

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

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