Copy code The code is as follows:
/* UTF-8 Chinese character truncation program*/
$str = "123 This is the test string";
$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; //The human understandable string length
$all_len = strlen($str); //Machine understands string length
if($length > $all_len)
{
return $str;
}
for($i = 0 ;$i < $all_len;)
{
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 < $length;)
{
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);
}
?>
In fact, PHP has a native character interception scheme under multi-charset, um, so it looks like this... 囧..
In the Multibyte String Functions function family,
string mb_substr ( string $str , int $start [, int $length [, string $encoding ]] ) is used to intercept strings
int mb_strlen ( string $str [, string $encoding ] ) returns characters String length
....
Please check the PHP manual for details
http://www.bkjia.com/PHPjc/326024.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/326024.htmlTechArticleCopy the code code as follows: ?php /* UTF-8 Chinese character truncation program*/ $str = "123this Is the test string"; $str1 = "()()"; echo subUTF8str($str,0,3)."br"; echo subUTF8str($str,0,4)...