Resolve the problem of using substr to intercept Es1EN 8 Chinese string with garbled code

  • 2020-06-15 07:57:01
  • OfStack

We know that sometimes when substr is used to intercept the Chinese characters of ES1en-8, there will often be messy code. Why this problem occurs? This article tells you the answer.
Look at this 1 piece of code (es3EN-8) :

<?
$str = ' All know strlen with mb_strlen It's a function to find the length of a string ';
echo strlen($str)'.<br />'.mb_strlen($str,'utf-8');
?>

Run the above code and the return value is as follows:
66
34
How's that? In strlen, Chinese is 3 bytes long and English is 1 byte long! In mb_strlen, the length is calculated as 1 byte! Therefore, when we use substr to intercept the Es16EN-8 Chinese string, we often get confused code, which is why!
Here is a function that intercepts the UTF-8 string:

function cutstr($sourcestr,$cutlength){
$returnstr = '';
$i = 0;
$n = 0;
$str_length = strlen($sourcestr);
$mb_str_length = mb_strlen($sourcestr,'utf-8');
while(($n < $cutlength) && ($i <= $str_length)){
$temp_str = substr($sourcestr,$i,1);
$ascnum = ord($temp_str);
if($ascnum >= 224){
$returnstr = $returnstr.substr($sourcestr,$i,3);
$i = $i + 3;
$n++;
}
elseif($ascnum >= 192){
$returnstr = $returnstr.substr($sourcestr,$i,2);
$i = $i + 2;
$n++;
}
elseif(($ascnum >= 65) && ($ascnum <= 90)){
$returnstr = $returnstr.substr($sourcestr,$i,1);
$i = $i + 1;
$n++;
}
else{
$returnstr = $returnstr.substr($sourcestr,$i,1);
$i = $i + 1;
$n = $n + 0.5;
}
}
if ($mb_str_length > $cutlength){
$returnstr = $returnstr . "...";
}
return $returnstr; 
}

Use examples:

<?
$str = ' Longest period of validity 3 The system will delete this information automatically after the expiry date ';
//echo strlen($str);
//echo '<hr />'.mb_strlen($str,'utf-8');
echo '<hr />'.$str;
echo '<hr />'.cutstr($str,24);
?>

Related articles: