php擷取字串,避免亂碼

2022-06-23 06:09:09 字數 911 閱讀 5464

1. 擷取gb2312中文字串 

<?php

//擷取中文字串

function mysubstr($str, $start, $len) else

$tmpstr .= substr($str, $i, 1);

} return $tmpstr;

} ?>

2. 擷取utf8編碼的多位元組字串  

<?php

//擷取utf8字串

function utf8substr($str, $from, $len)

'.

'((?:[\x00-\x7f]|[\xc0-\xff][\x80-\xbf]+)).*#s',

'$1',$str);

} ?>

3. utf-8、gb2312都支援的漢字擷取函式  

<?php

function cut_str($string, $sublen, $start = 0, $code = 'utf-8')

else

else

} if(ord(substr($string, $i, 1))>129) $i++;

} if(strlen($tmpstr)<$strlen ) $tmpstr.= "...";

return $tmpstr;

} }

$str = "abcd需要擷取的字串";

echo cut_str($str, 8, 0, 'gb2312');

?>

4. bugfree 的字元擷取函式  

php擷取字串,出現亂碼

在資料庫中得到的字段太長了,不好直接在頁面顯示,所以我使用了一些擷取字串的方法。一在php manual中找到了substr方法,開始還挺驚喜。發現擷取中文的時候在字串的末尾出現亂碼。我用這個 方法擷取的是gb2312的中文字串,比如,我的字串 發現擷取中文的 substr 發現擷取中文的 0,4 ...

PHP擷取字串

php 自帶幾種字串擷取函式,其中常用到的就是 substr 和 mb substr。前者在處理中文時,gbk 為 2 個長度單位,utf 為 3 個長度單位,後者指定編碼後,乙個中文即為 1 個長度單位。substr 不用說,有時會截 1 3 個中文或半個中文,當然顯示出來是亂碼了,相對來說 mb...

PHP擷取字串

php 構造字串 str abcdefghijklmnopqrstuvwxyz echo 原字串 str.按各種方式進行擷取 str1 substr str,5 echo 從第5個字元開始取至最後 str1.str2 substr str,9,4 echo 從第9個字元開始取4個字元 str2.st...