初學下面這個PHP Substr庫函數程式不算完美,但處理一般的中文(GB18030,GB2312,BIG5)是沒有問題的。這個函數不適合utf-8編碼的文字。
- //$str字串
- //$max 最大字元數
- function Substring($str,$max){
- $cnt=0; //實際計數
- $index=0; //當前索引
- $output=''; //輸出
- //
- while($cnt<$max && $index<strlen($str)){
- $output.=$str[$index];
- //big5
- if(ord($str[$index])>=0x81 &&
ord($str[$index])<=0xfe){
- if($index+1<strlen($str)){
- if( (ord($str[$index+1])>=0x40
&& ord($str[$index+1])<0x7e)
- || (ord($str[$index+1])>=0xa1
&& ord($str[$index+1])<=0xfe) ){
- $index++;
- $output.=$str[$index];
- }
- }
- }
- //gb2312
- else if(ord($str[$index])>=0xa1
&& ord($str[$index])<=0xf7){
- $output.=$str[$index];
- if($index+1<strlen($str)){
- if(ord($str[$index+1])>=0xa1
&& ord($str[$index+1])<0xfe){
- $index++;
- $output.=$str[$index];
- }
- }
- }
- else{
- }
- $cnt++;
- $index++;
- }
- return $output;
- }
以上程式碼範例就是PHP Substr庫函數在截取中文字元時的具體使用方法。
http://www.bkjia.com/PHPjc/446214.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/446214.htmlTechArticle初學 下面這個PHP Substr庫函數程式不算完美,但處理一般的中文(GB18030,GB2312,BIG5)是沒有問題的。這個函數不適合utf-8編碼的文字。 //$str字元...