国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

首頁 后端開發(fā) php教程 如何在保持字邊界的同時精確截斷多字節(jié)字符串?

如何在保持字邊界的同時精確截斷多字節(jié)字符串?

Dec 07, 2024 pm 03:01 PM

How Can I Precisely Truncate Multibyte Strings While Maintaining Word Boundaries?

精確截斷多字節(jié)字符串

簡介

將字符串截斷為特定字符長度是編程中的常見任務(wù)。但是,在處理可能包含不同寬度的字符的多字節(jié)字符串時,它會變得更加復(fù)雜。這個問題深入研究了截斷多字節(jié)字符串同時保留字邊界的細(xì)微差別。

PHP 的 mb_strimwidth 函數(shù)

正如答案所建議的,PHP 提供了一個名為 mb_strimwidth 的便捷函數(shù)( ) 處理多字節(jié)字符串的截斷。它采用字符串、所需的寬度和可選的終止符作為參數(shù)。但是,此函數(shù)不考慮單詞邊界。

自定義截斷算法

要實現(xiàn)單詞邊界截斷,可以使用自定義算法:

function truncate($string, $chars = 50, $terminator = ' …') {
    // Calculate the maximum length considering the terminator
    $max_length = $chars - mb_strlen($terminator);

    // Short circuit for strings shorter than the maximum length
    if (mb_strlen($string) <= $max_length) {
        return $string;
    }

    // Find the last space character within the maximum length
    $last_space_index = mb_strrpos($string, ' ', $max_length);

    // Cut the string at the last space or at the maximum length if no last space is found
    $truncated_string = (false !== $last_space_index)
        ? mb_substr($string, 0, $last_space_index)
        : mb_strimwidth($string, 0, $chars);

    // Append the terminator
    $truncated_string .= $terminator;

    return $truncated_string;
}

該函數(shù)實現(xiàn)了中描述的步驟問題:

  1. 計算最大長度。
  2. 驗證字符串是否比最大長度長。
  3. 找到低于最大長度的最后一個空格字符。
  4. 相應(yīng)地剪切字符串。
  5. 附加終止符。
  6. 返回截斷的字符串。

演示

下面的代碼演示了自定義截斷的用法函數(shù):

$in = "Answer to the Ultimate Question of Life, the Universe, and Everything.";
$out = truncate($in, 50, ' …');

echo $out; // "Answer to the Ultimate Question of Life, the …"

結(jié)論

PHP 的 mb_strimwidth() 函數(shù)提供了一種截斷多字節(jié)字符串的簡單方法,但它不考慮字邊界。通過實現(xiàn)自定義算法,我們可以實現(xiàn)更精確的截斷,從而保留單詞邊界的完整性。

以上是如何在保持字邊界的同時精確截斷多字節(jié)字符串?的詳細(xì)內(nèi)容。更多信息請關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

本站聲明
本文內(nèi)容由網(wǎng)友自發(fā)貢獻(xiàn),版權(quán)歸原作者所有,本站不承擔(dān)相應(yīng)法律責(zé)任。如您發(fā)現(xiàn)有涉嫌抄襲侵權(quán)的內(nèi)容,請聯(lián)系admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費脫衣服圖片

Undresser.AI Undress

Undresser.AI Undress

人工智能驅(qū)動的應(yīng)用程序,用于創(chuàng)建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用于從照片中去除衣服的在線人工智能工具。

Clothoff.io

Clothoff.io

AI脫衣機(jī)

Video Face Swap

Video Face Swap

使用我們完全免費的人工智能換臉工具輕松在任何視頻中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的代碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

功能強(qiáng)大的PHP集成開發(fā)環(huán)境

Dreamweaver CS6

Dreamweaver CS6

視覺化網(wǎng)頁開發(fā)工具

SublimeText3 Mac版

SublimeText3 Mac版

神級代碼編輯軟件(SublimeText3)

如何在PHP中實施身份驗證和授權(quán)? 如何在PHP中實施身份驗證和授權(quán)? Jun 20, 2025 am 01:03 AM

tosecurelyhandleauthenticationandationallizationInphp,lofterTheSesteps:1.AlwaysHashPasswordSwithPassword_hash()andverifyusingspasspassword_verify(),usepreparedStatatementStopreventsqlineptions,andStoreSeruserDatain usseruserDatain $ _sessiveferterlogin.2.implementrole-2.imaccessccsccccccccccccccccccccccccc.

我如何了解最新的PHP開發(fā)和最佳實踐? 我如何了解最新的PHP開發(fā)和最佳實踐? Jun 23, 2025 am 12:56 AM

TostaycurrentwithPHPdevelopmentsandbestpractices,followkeynewssourceslikePHP.netandPHPWeekly,engagewithcommunitiesonforumsandconferences,keeptoolingupdatedandgraduallyadoptnewfeatures,andreadorcontributetoopensourceprojects.First,followreliablesource

什么是PHP,為什么它用于Web開發(fā)? 什么是PHP,為什么它用于Web開發(fā)? Jun 23, 2025 am 12:55 AM

PHPbecamepopularforwebdevelopmentduetoitseaseoflearning,seamlessintegrationwithHTML,widespreadhostingsupport,andalargeecosystemincludingframeworkslikeLaravelandCMSplatformslikeWordPress.Itexcelsinhandlingformsubmissions,managingusersessions,interacti

如何設(shè)置PHP時區(qū)? 如何設(shè)置PHP時區(qū)? Jun 25, 2025 am 01:00 AM

tosetTherightTimeZoneInphp,restate_default_timezone_set()functionAtthestArtofyourscriptWithavalIdidentIdentifiersuchas'america/new_york'.1.usedate_default_default_timezone_set_set()

如何在操作系統(tǒng)(Windows,MacOS,Linux)上安裝PHP? 如何在操作系統(tǒng)(Windows,MacOS,Linux)上安裝PHP? Jun 20, 2025 am 01:02 AM

安裝PHP的方法因操作系統(tǒng)而異,以下是具體步驟:1.Windows用戶可使用XAMPP一鍵安裝包或手動配置,下載XAMPP并安裝,選擇PHP組件或?qū)HP加入環(huán)境變量;2.macOS用戶可通過Homebrew安裝PHP,運行相應(yīng)命令安裝并配置Apache服務(wù)器;3.Linux用戶(Ubuntu/Debian)可使用APT包管理器更新源后安裝PHP及常用擴(kuò)展,并通過創(chuàng)建測試文件驗證安裝是否成功。

我如何驗證PHP中的用戶輸入以確保其符合某些標(biāo)準(zhǔn)? 我如何驗證PHP中的用戶輸入以確保其符合某些標(biāo)準(zhǔn)? Jun 22, 2025 am 01:00 AM

TovalidateuserinputinPHP,usebuilt-invalidationfunctionslikefilter_var()andfilter_input(),applyregularexpressionsforcustomformatssuchasusernamesorphonenumbers,checkdatatypesfornumericvalueslikeageorprice,setlengthlimitsandtrimwhitespacetopreventlayout

如何使用session_destroy()在PHP中破壞會話? 如何使用session_destroy()在PHP中破壞會話? Jun 20, 2025 am 01:06 AM

要完全銷毀PHP中的會話,必須先調(diào)用session_start()啟動會話,再調(diào)用session_destroy()刪除所有會話數(shù)據(jù)。1.首先使用session_start()確保會話已啟動;2.然后調(diào)用session_destroy()清除會話數(shù)據(jù);3.可選但推薦:手動unset$_SESSION數(shù)組以清除全局變量;4.同時刪除會話cookie,防止用戶保留會話狀態(tài);5.最后注意在銷毀后重定向用戶,并避免立即復(fù)用會話變量,否則需重新啟動會話。這樣做能確保用戶徹底退出系統(tǒng),不留殘留信息。

什么是php(serialize(),Unserialize())中的數(shù)據(jù)序列化? 什么是php(serialize(),Unserialize())中的數(shù)據(jù)序列化? Jun 22, 2025 am 01:03 AM

thephpfunctionserize()andunSerialize()redustoconvertComplexdatStructDestoresToroStoroStoroSandaBackagagain.1.Serialize()

See all articles