一起源码网

  • www.171739.xyz
  • 全球最大的互联网技术和资源下载平台
搜索
猜你喜欢
查看: 3937|回复: 1
打印 上一主题 下一主题

适用于不同编码的中文字符串截取函数代码实例汇总

[复制链接]

0

主题

0

帖子

1万

积分

钻石会员

Rank: 8Rank: 8

积分
17424
QQ
跳转到指定楼层
楼主
发表于 2020-3-24 11:30 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
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; 
} 
?>

2. 适用于utf8

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

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['utf-8']   = "/[x01-x7f]|[xc2-xdf][x80-xbf]|[xe0-xef][x80-xbf]{2}|[xf0-xff][x80-xbf]{3}/";    
 $re['gb2312'] = "/[x01-x7f]|[xb0-xf7][xa0-xfe]/";   
 $re['gbk']   = "/[x01-x7f]|[x81-xfe][x40-xfe]/";   
 $re['big5']   = "/[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;   
}

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); 
?>

分享到:  QQ好友和群QQ好友和群
收藏收藏
回复

使用道具 举报

0

主题

20

帖子

146

积分

注册会员

Rank: 2

积分
146
沙发
发表于 2022-9-11 15:12 | 只看该作者
计算机源代码
回复

使用道具 举报

一起源码让程序更轻更快

www.171739.xyz

工作时间 周一至周六 8:00-17:30

侵权处理

客服QQ点击咨询

关注抖音号

定期抽VIP

Copyright © 2016-2021 https://www.171739.xyz/ 滇ICP备13200218号

快速回复 返回顶部 返回列表