php Custom Function to Intercept Chinese Character Length

  • 2021-06-28 11:29:43
  • OfStack

 
function msubstr($str,$start,$len) { 
$strlen=$start+$len; 
for($i=0;$i<$strlen;$i++) { 
if(ord(substr($str,$i,1))>0xa0) { 
$tmpstr.=substr($str,$i,2); 
$i++; 
} else 
$tmpstr.=substr($str,$i,1); 
} 
return $tmpstr; 

} 

 
<?PHP 
$str=" How long is this character? ,^_^"; 
$Short_Str=showShort($str,4);// Before interception 4 Chinese characters , The result is : This character ... 
Echo "$Short_Str"; 
Function csubstr($str,$start,$len) 
{ 
$strlen=strlen($str); 
$clen=0; 
for($i=0;$i<$strlen;$i++,$clen++) 
{ 
if ($clen>=$start+$len) 
break; 
if(ord(substr($str,$i,1))>0xa0) 
{ 
if ($clen>=$start) 
$tmpstr.=substr($str,$i,2); 
$i++; 
} 
else 
{ 
if ($clen>=$start) 
$tmpstr.=substr($str,$i,1); 
} 
} 

return $tmpstr; 
} 
Function showShort($str,$len) 
{ 
$tempstr = csubstr($str,0,$len); 
if ($str<>$tempstr) 
$tempstr .= "..."; // What do you want to end with , Modify here to do so . 

return $tempstr; 
} 

Let's see how nagging works. Is it simple?
 
$len = 19; 
$text = " How to show long headlines of news just in front 1 Some words, followed by ..... Come instead? "; 
echo strlen($text)<=$len ? $text : (substr($text,0,$len).chr(0)."...."); 

Related articles: