close

在 PHP 中使用 substr 截取 utf-8 字串,會造成取得字串出現如下亂碼。

$str="測試字串測試字串測試字串測試字串";
echo substr($str,0,10);

image 

可以直接將所需要截取的  utf-8 字串長度乘上 3,可直接取得正確的字串內容。

$str="測試字串測試字串測試字串測試字串";
echo substr($str,0,3*3);

 image

但是字串中包含其它非 utf-8 內的 ASCII 碼,會使得直接乘上 3 所取得的字串長度,跟原先的

字串長度不符合,而造成亂碼。

$str="測試字a串測試字串測試字串測試字串";
echo substr($str,0,10*3);

image

 

在 PHP 中,他提供了 mb_substr ,他可以幫我們正確的截取我們需要的 utf-8 字串,解決使

用 substr 截取 utf-8 字串會產生亂碼的問題。

$str="測試字串a測試字串測試字串測試字串";
echo mb_substr($str,0,10,'utf8');

image

 

參考網站:http://php.net/manual/en/function.mb-substr.php

arrow
arrow
    全站熱搜

    iammic 發表在 痞客邦 留言(0) 人氣()