首頁  >  文章  >  後端開發  >  substr(),mb_substr()及mb_strcut的區別與用法(中文字元截取)

substr(),mb_substr()及mb_strcut的區別與用法(中文字元截取)

巴扎黑
巴扎黑原創
2016-11-23 14:11:131169瀏覽

PHP substr()函數可以分割文字,但要分割的文字如果包含中文字元往往會遇到問題,這時可以用mb_substr()/mb_strcut這個函數,mb_substr() /mb_strcut的用法與substr()相似,只是在mb_substr()/mb_strcut最後要加入多一個參數,以設定字串的編碼,但是一般的伺服器都沒開啟php_mbstring.dll,需要在php.ini在把php_mbstring.dll開啟。

舉個例子: 

<?php 
echo mb_substr(&#39;这样一来我的字符串就不会有乱码^_^&#39;, 0, 7, &#39;utf-8&#39;); 
?>

輸出:這樣一來我的字 

<?php 
echo mb_strcut(&#39;这样一来我的字符串就不会有乱码^_^&#39;, 0, 7, &#39;utf-8&#39;); 
?>

輸出:這樣 
從上面的例子可以看出,mb_substr是按字來切分字符,而 
從上面的例子可以看出,mb_substr切分字符,但是都不會產生半個字符的現象…… 

mbstring 函數的說明: 

php的mbstring擴展模組提供了多字節字符的處理能力,平常最常用的就是用mbstring來切分多位元組的中文字符,這樣可以避免半個字符的情況,由於是php的擴展,它的性能也要比一些自定義的多字節切分函數要好上一些。 

mbstring extension提供了幾個功能類似的函數,mb_substr和mb_strcut,看看手冊上對它們的解釋。

mb_substr 
mb_substr() returns the portion of str specified by the start and length parameters. 

mb_substr() performs multi-byte safe substror oper substr() performs multi-byte safe subgined) . character's position is 0. Second character position is 1, and so on. 

mb_strcut 
mb_strcut() returns the portion of str specified by the start and length parawper​​peration estr而且) with different method . If start position is multi-byte character's second byte or larger, it starts from first byte of multi-byte character. 

It subtracts string from stror that that shorter than that a not or not strorn that thatis再舉比較 
mb_strcut:我是 

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