Home  >  Article  >  Backend Development  >  PHP UTF8 Chinese character truncation function code_PHP tutorial

PHP UTF8 Chinese character truncation function code_PHP tutorial

WBOY
WBOYOriginal
2016-07-21 15:15:47916browse

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

www.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)...
Statement:
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