Home > php教程 > php手册 > PHP UTF8中文字符截断函数代码

PHP UTF8中文字符截断函数代码

WBOY
Release: 2016-06-13 11:57:36
Original
1544 people have browsed it

复制代码 代码如下:


/* UTF-8中文字符截断程序 */
$str = "123这是测试字符串";
$str1 = "()()";
echo subUTF8str($str,0,3)."
";
echo subUTF8str($str,0,4)."
";
echo subUTF8str($str1,0,4)."
";
echo subUTF8str($str1,0,10)."
";
function subUTF8str($str,$start=0,$length=80){
$cur_len = 0; //人理解的字符串长度
$all_len = strlen($str); //机器理解字符串长度
if($length > $all_len)
{
return $str;
}
for($i = 0;$i {
if($cur_len == $start)
{
break;
}
if (ord($str[$i]) > 127)
{
$i += 3;
}else{
$i += 1;
}
$cur_len ++;
}
$start_pos = $i;
$temp_pos = $cur_len;
for(;$cur_len - $temp_pos {
if($i >= $all_len)
break;
if (ord($str[$i]) > 127)
{
$i += 3;
}else{
$i += 1;
}
$cur_len ++;
}
$end_pos = $i;
return substr($str,$start_pos,$end_pos);
}
?>


其实,PHP原生就有多charset下字符截取方案,额,所以就是这个样子...囧..
Multibyte String Functions函数族中,

string mb_substr ( string $str , int $start [, int $length [, string $encoding ]] ) 用来字符串截取
int mb_strlen ( string $str [, string $encoding ] ) 返回字符串长度
....
详细请查看PHP手册
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template