Home >Backend Development >PHP Tutorial >How to separate full-width and half-width to avoid garbled characters_PHP tutorial
function ChgTitle($title)
{
$length = 46;
if (strlen($title)>$length) {
$temp = 0;
for( $i=0; $i<$length; $i++)
if (ord($title[$i]) > 128)
$temp++;
if ($temp%2 == 0 )
$title = substr($title,0,$length)."...";
else
$title = substr($title,0,$length+1).".. .";
}
return $title;
}
The principle is to truncate a character and see if its ASCII code is greater than 128. If so, it means that the truncated character is a full-width Chinese character. , then go back and cut off. Use $length to control the length
Note: Loop to determine the number of characters >128 in the string. If the half-width character is an even number, it means that the position is exactly the entire Chinese character. If it is an odd number, it is half a Chinese character. , need to remove a character