標籤:c style class blog code java
<?phpheader("content-type:text/html;charset=utf-8");$str = "1個中文字utf-8編碼";/*** $b utf-8用 3 , gb2312用2*/function test($str , $b=3){ $length = strlen($str); $rets = ‘‘; for($i = 0 ; $i<$length ; $i ++){ if(ord(substr($str , $i,1))>128){ $rets[] = substr($str ,$i,$b); $i += $b-1; }else{ $rets[] = substr($str, $i,1); } } return implode(‘‘ , array_reverse($rets)); } $test = test($str);var_dump($test);/**string(24) "碼編8-ftu字文中個1" */
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /></head><body><?php$a=‘abcd閔LOVE軍兒‘;//測試的字串,包含中文西文//下面的測試輸出為上,因為在編碼為utf-8時,一個中文字元佔3個長度//echo strlen(‘閔‘); $b=‘‘;$i=0;while($i<strlen($a)){ if(ord(substr($a,$i,1))>0xa0)//ord函數判斷該字串是否是中文 { $b=substr($a,$i,3).$b;//這句很重要,倒序! $i+=3; } else { $b=substr($a,$i,1).$b; $i++; }}echo $b;?></body></html>
<?php
header("content-type:text/html;charset=utf-8");
$str = "1個中文字utf-8編碼";
/**
* $b utf-8用 3 , gb2312用2
*/
function test($str , $b=3){
$length = strlen($str);
$rets = ‘‘;
for($i = 0 ; $i<$length ; $i ++){
if(ord(substr($str , $i,1))>128){
$rets[] = substr($str ,$i,$b);
$i += $b-1;
}else{
$rets[] = substr($str, $i,1);
}
}
return implode(‘‘ , array_reverse($rets));
}
$test = test($str);
var_dump($test);
/**
string(24) "碼編8-ftu字文中個1"
*/