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;  

相关文章

PHP实现的简易版图片相似度比较

由于相似图片搜索的php实现的 API 不怎么符合我的用途,所以我重新定义 API 的架构,改写成比较简单的函数方式,虽然还是用对象的方式包装。 复制代码 代码如下: <?...

PHP memcache扩展的三种安装方法

关于比较请看http://code.google.com/p/memcached/wiki/PHPClientComparison。推荐使用新的memcached,安装方法基本同下面,只...

php实现通用的信用卡验证类

本文实例讲述了php实现通用的信用卡验证类。分享给大家供大家参考。 原文说明如下: Credit Card Validation Solution (PHP Edition) Vers...

php mssql 分页SQL语句优化 持续影响

复制代码 代码如下:<?php /** * @Filename :page.sql.class.php * @CreatTime :2009-01-06 * @Descrition...

PHP session会话操作技巧小结

PHP session会话操作技巧小结

本文实例总结了PHP session会话操作技巧。分享给大家供大家参考,具体如下: 会话技术 session 将会话数据存储与服务器端,同时使会话数据可以区分浏览器 为每个会话数据建立独...