1.先算再取
/**
* Author : Dummy | Zandy
* Email : lianxiwoo@gmail.com | hotmail.com
* Create : 200512
* Usage : echo join('', String::subString_UTF8('汉字', 0, 1));
*/
ini_set('display_errors', 1);
error_reporting(E_ALL ^ E_NOTICE);
class String {
function subString_UTF8($str, $start, $lenth)
{
$len = strlen($str);
$r = array();
$n = 0;
$m = 0;
for($i = 0; $i < $len; $i++) {
$x = substr($str, $i, 1);
$a = base_convert(ord($x), 10, 2);
$a = substr('00000000'.$a, -8);
if ($n < $start){
if (substr($a, 0, 1) == 0) {
}elseif (substr($a, 0, 3) == 110) {
$i += 1;
}elseif (substr($a, 0, 4) == 1110) {
$i += 2;
}
$n++;
}else{
if (substr($a, 0, 1) == 0) {
$r[] = substr($str, $i, 1);
}elseif (substr($a, 0, 3) == 110) {
$r[] = substr($str, $i, 2);
$i += 1;
}elseif (substr($a, 0, 4) == 1110) {
$r[] = substr($str, $i, 3);
$i += 2;
}else{
$r[] = '';
}
if (++$m >= $lenth){
break;
}
}
}
return $r;
} // End subString_UTF8
}// End String
echo join('', String::subString_UTF8('汉字', 0, 1));
2.先截后取
这种方式凉鞋觉得很巧妙……
用传统截取函数先截断……
然后判断中文单个字符是否被分割开……
如果是……则处理之……
要特别注意的是 substr 函数的第三个参数必须大于 3 ……
至于为什么不用凉鞋解释了吧?
// A trim function to remove the last character of a utf-8 string
// by following instructions on http://en.wikipedia.org/wiki/UTF-8
// dotann
// usage: $str = utf8_trim(substr($str,0,50));
function utf8_trim($str) {
$len = strlen($str);
for ($i=strlen($str)-1; $i>=0; $i-=1){
$hex .= ' '.ord($str[$i]);
$ch = ord($str[$i]);
if (($ch & 128)==0) return(substr($str,0,$i));
if (($ch & 192)==192) return(substr($str,0,$i));
}
return($str.$hex);
}
$str = '汉字';
echo utf8_trim(substr($str,0,3));
3.还有其它方法,
比如 007pig 为我们 vBulletin 中文版里所写的函数