Home > Backend Development > PHP Tutorial > Summary of Chinese string interception function code examples suitable for different encodings

Summary of Chinese string interception function code examples suitable for different encodings

伊谢尔伦
Release: 2023-03-14 09:08:01
Original
1362 people have browsed it

1. 适用于GB2312中文字符串

<?php 
//截取中文字符串 
function mysubstr($str, $start, $len) { 
$tmpstr = ""; 
$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; 
} 
?>
Copy after login

2. 适用于utf8

<?php 
//截取utf8字符串 
function utf8Substr($str, $from, $len) 
{ 
return preg_replace(&#39;#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,&#39;.$from.&#39;}&#39;. 
&#39;((?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,&#39;.$len.&#39;}).*#s&#39;, 
&#39;$1&#39;,$str); 
} 
?>
Copy after login

3。全部都适用

function csubstr($str, $start=0, $length, $charset="utf-8", $suffix=true)   
{   
 if(function_exists("mb_substr"))   
  return mb_substr($str, $start, $length, $charset);   
 $re[&#39;utf-8&#39;]   = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";    
 $re[&#39;gb2312&#39;] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";   
 $re[&#39;gbk&#39;]   = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";   
 $re[&#39;big5&#39;]   = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";    
 preg_match_all($re[$charset], $str, $match);   
 $slice = join("",array_slice($match[0], $start, $length));   
 if($suffix) return $slice."…";   
 return $slice;   
}
Copy after login

4. BugFree 的字符截取函数

<?php 
function sysSubStr($String,$Length,$Append = false) 
{ 
if (strlen($String) <= $Length ) 
{ 
return $String; 
} 
else 
{ 
$I = 0; 
while ($I < $Length) 
{ 
$StringTMP = substr($String,$I,1); 
if ( ord($StringTMP) >=224 ) 
{ 
$StringTMP = substr($String,$I,3); 
$I = $I + 3; 
} 
elseif( ord($StringTMP) >=192 ) 
{ 
$StringTMP = substr($String,$I,2); 
$I = $I + 2; 
} 
else 
{ 
$I = $I + 1; 
} 
$StringLast[] = $StringTMP; 
} 
$StringLast = implode("",$StringLast); 
if($Append) 
{ 
$StringLast .= "..."; 
} 
return $StringLast; 
} 
}$String = "www.at0915.cn"; 
$Length = "18"; 
$Append = false; 
echo sysSubStr($String,$Length,$Append); 
?>
Copy after login

The above is the detailed content of Summary of Chinese string interception function code examples suitable for different encodings. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template