本文目錄一覽:
如何利用PHP來截取一段中文字元串而不出現亂碼
/*
功能:截取全形和半形混合的字元串以避免亂碼
參數:
$str_cut 需要截斷的字元串
$length 允許字元串顯示的最大長度
*/
function substr_cut($str_cut,$length = 30){
if (strlen($str_cut) ; $length){
for($i=0; $i $length; $i++)
if (ord($str_cut[$i]) ; 128) $i++;
$str_cut = substr($str_cut,0,$i) . “…”;
}
return $str_cut;
}
說明:
程序的關鍵語句是:
for($i=0; $i $length; $i++)
if (ord($str_cut[$i]) ; 128) $i++;
$str_cut = substr($str_cut,0,$i) . “…”;
如果字元的ASCII碼大於128,說明當前字元和下一個字元是屬於一個漢字的。
則,$i++ 跳過對下一個字元的判斷。
再結合循環中的 $i++ ,實際上,當遇到一個漢字時,$i 就會加 2 ,從而正確的跳過漢字。
最終實現的效果是,$i 變數指向的要麼是半形的字元,要麼是全形漢字的首字元,不會指向
全形漢字的第二個字元,所以,當$i ;= $length 時,循環結束,使用
$str_cut = substr($str_cut,0,$i) . “…”; 截取字元時自然也就不會出現亂碼了。
本人在寫一個程序時需要利用PHP從一段字元串中截取指定長度的一段字元下來。以前在寫ASP的時候,參考動網的程序寫過類似的程序,不過,還沒用PHP寫過。
想偷懶,看有不有現成的代碼可以用。於是,在GOOGLE中輸入:PHP 截斷字元 後查找到一段代碼。
[php]如何在PHP中截取中文字串無亂碼
一年前寫的一個函數。用法與substr一樣,支持中文。您也可以加以改進。
//截取字元串含數,對系統函數的改進,不會將中文變亂。
function mysubstr ($str,$start,$len=0,$cutchar=”…”) {
$str=str_replace(” “,’ ‘,$str);
$str=str_replace(“「”,’「’,$str);
$str=str_replace(“」”,’」’,$str);
$str=str_replace(“—”,’—’,$str);
$str=str_replace(“””,'”‘,$str);
$str=str_replace(”’,”‘”,$str);
$str=str_replace(“”,”,$str);
$str=str_replace(“”,”,$str);
$str=str_replace(“”,”,$str);
$str=preg_replace(“/[\s]+/”,” “,$str);
$tolen=strlen($str);
if(!($start==0 $len=$tolen)){
//為方便操作,先將起始值和長度值轉換為正數
if($start0)$start=$tolen+$start;if($start0)$start=0;if($start$tolen)return “”;
if($len=0)$len=($tolen+$len)-$start;if($len1)return “”;
if($len$tolen)$len=$tolen;
for($i=0;$i$start;$i++){
if(ord(substr($str,$i,1))127){$i++;}
}
$start=$i; //起始位置計算完成
for($k=0;$k$len;$k++,$i++){
if(ord(substr($str,$i,1))127){$i++;$k++;}
}
$len=$k; //長度計算完成
$str=substr($str,$start,$len);
if($start0){$str=$cutchar.$str;}
if($start+$len$tolen){$str.=$cutchar;}
}
$str=str_replace(“”,”,$str);
$str=str_replace(‘”‘,'”‘,$str);
$str=str_replace(“‘”,”’,$str);
$str=str_replace(“”,”,$str);
$str=str_replace(“”,”,$str);
return $str;
}
php 如何實現中文無亂碼截取用哪個函數
中文截取:mb_substr()
mb_substr( $str, $start, $length, $encoding )
$str,需要截斷的字元串
$start,截斷開始處,起始處為0
$length,要截取的字數
$encoding,網頁編碼,如utf-8,GB2312,GBK
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/282826.html