php中支持多种编码的中文字符串截取函数!

yipeiwu_com6年前PHP代码库
支持多种编码的中文字符串截取函数!  
复制代码 代码如下:

/*  
  * @todo 中文截取,支持gb2312,gbk,utf-8,big5   
  *  
  * @param string $str 要截取的字串  
  * @param int $start 截取起始位置  
  * @param int $length 截取长度  
  * @param string $charset utf-8|gb2312|gbk|big5 编码   
  * @param $suffix 是否加尾缀  
  */   

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;  

相关文章

phpstorm配置Xdebug进行调试PHP教程

phpstorm配置Xdebug进行调试PHP教程

运行环境: PHPSTORM版本 : 8.0.1 PHP版本 : 5.6.2 xdebug版本:php_xdebug-2.2.5-5.6-vc11-x86_64.dll ps : php...

PHP中其实也可以用方法链

简单示意一下: 复制代码 代码如下: <?php class test { private $_name = ''; public function setName($name)...

详解PHP中mb_strpos的使用

mb_strpos (PHP 4 >= 4.0.6, PHP 5, PHP 7) mb_strpos — Find position of first occurrence of...

PHP自定义函数实现数组比较功能示例

本文实例讲述了PHP自定义函数实现数组比较功能。分享给大家供大家参考,具体如下: <?php //数组使用标准比较运算符这样比较的 function standar...

PHP扩展Memcache分布式部署方案

基础环境 其实基于PHP扩展的Memcache客户端实际上早已经实现,而且非常稳定。先解释一些名词,Memcache是danga.com的一个开源项目,可以类比于MySQL这样的服务,...