1.  
  1. 在做PHP开发的时候,由于我国的语言环境问题,所以我们常常需要对中文进行处理。在PHP中,我们都知道有专门的mb_substrmb_strlen函数,可以对中文进行截取和计算长度,但是,由于这些函数并非PHP的核心函数,所以,它们常常有可能没有开启。当然,如果是用的自己的服务器,则只要在php.ini中开启即可。如果是用的虚拟主机,而服务器又没有开启这方面的函数的话,那就需要我们自己写出点适合咱国情的函数来了。
  2.  
  3. 以下几个函数用起来颇为顺手的。不过要知道,得在utf-8环境下使用。
  1. header('Content-type:text/html;charset=utf-8');
  2. /**
  3. * 可以统计中文字符串长度的函数
  4. * @param $str 要计算长度的字符串
  5. * @param $type 计算长度类型,0(默认)表示一个中文算一个字符,1表示一个中文算两个字符
  6. *
  7. */
  8. function abslength($str)
  9. {
  10. if(empty($str)){
  11. return 0;
  12. }
  13. if(function_exists('mb_strlen')){
  14. return mb_strlen($str,'utf-8');
  15. }
  16. else {
  17. preg_match_all("/./u", $str, $ar);
  18. return count($ar[0]);
  19. }
  20. }
  21. $str = '我们都是中国人啊,ye!';
  22. $len = abslength($str);
  23. var_dump($len); //return 12
  24. $len = abslength($str,'1');
  25. echo '<br />'.$len; //return 22
  26.  
  27. /*
  28. utf-8编码下截取中文字符串,参数可以参照substr函数
  29. @param $str 要进行截取的字符串
  30. @param $start 要进行截取的开始位置,负数为反向截取
  31. @param $end 要进行截取的长度
  32. */
  33. function utf8_substr($str,$start=0) {
  34. if(empty($str)){
  35. return false;
  36. }
  37. if (function_exists('mb_substr')){
  38. if(func_num_args() >= 3) {
  39. $end = func_get_arg(2);
  40. return mb_substr($str,$start,$end,'utf-8');
  41. }
  42. else {
  43. mb_internal_encoding("UTF-8");
  44. return mb_substr($str,$start);
  45. }
  46.  
  47. }
  48. else {
  49. $null = "";
  50. preg_match_all("/./u", $str, $ar);
  51. if(func_num_args() >= 3) {
  52. $end = func_get_arg(2);
  53. return join($null, array_slice($ar[0],$start,$end));
  54. }
  55. else {
  56. return join($null, array_slice($ar[0],$start));
  57. }
  58. }
  59. }
  60. $str2 = 'wo要截取zhongwen';
  61. echo '<br />';
  62. echo utf8_substr($str2,0,-4); //return wo要截取zhon

支持gb2312,gbk,utf-8,big5 中文截取方法

  1. /*
  2.  
  3. * 中文截取,支持gb2312,gbk,utf-8,big5
  4.  
  5. *
  6.  
  7. * @param string $str 要截取的字串
  8.  
  9. * @param int $start 截取起始位置
  10.  
  11. * @param int $length 截取长度
  12.  
  13. * @param string $charset utf-8|gb2312|gbk|big5 编码
  14.  
  15. * @param $suffix 是否加尾缀
  16.  
  17. */
  18.  
  19. public function csubstr($str, $start=0, $length, $charset="utf-8", $suffix=true)
  20.  
  21. {
  22.  
  23. if(function_exists("mb_substr"))
  24.  
  25. {
  26.  
  27. if(mb_strlen($str, $charset) <= $length) return $str;
  28.  
  29. $slice = mb_substr($str, $start, $length, $charset);
  30.  
  31. }
  32.  
  33. else
  34.  
  35. {
  36.  
  37. $re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
  38.  
  39. $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
  40.  
  41. $re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
  42.  
  43. $re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
  44.  
  45. preg_match_all($re[$charset], $str, $match);
  46.  
  47. if(count($match[0]) <= $length) return $str;
  48.  
  49. $slice = join("",array_slice($match[0], $start, $length));
  50.  
  51. }
  52.  
  53. if($suffix) return $slice."…";
  54.  
  55. return $slice;
  56.  
  57. }

php中计算中文字符串长度、截取中文字符串的更多相关文章

  1. php 获取中文长度 截取中文字符串

    #获取中文长度mb_strlen($str,$encoding); #截取中文字符串 mb_substr(str,start,length,encoding);

  2. JS判断字符串长度(中文长度为2,英文长度为1)

    目的:计算字符串长度(英文占1个字符,中文汉字占2个字符) 方法一: String.prototype.gblen = function() { var len = 0; for (var i=0; ...

  3. 字符串长度截取换行/n

    /// <summary>        /// 格式化字符串长度,超出部分显示省略号,区分汉字跟字母.汉字2个字节,字母数字一个字节        /// </summary> ...

  4. [寒江孤叶丶的Cocos2d-x之旅_36]用LUA实现UTF8的字符串基本操作 UTF8字符串长度,UTF8字符串剪裁等

    原创文章,欢迎转载,转载请注明:文章来自[寒江孤叶丶的Cocos2d-x之旅系列] 博客地址:http://blog.csdn.net/qq446569365 一个用于UTF8字符串操作的类.功能比較 ...

  5. JS计算字符串长度(中文算2个)

    /** * @return {number} */ getRealLength = function(str) { var realLength = 0, len = str.length, char ...

  6. AX Dynamics 去中文字符长度:中文字符当2个字符处理

    static void jw_testStrByteLen(Args _args){    str _str = "A你好";                  System.Te ...

  7. EasyUI DataGrid 时间格式化、字符串长度截取

    需要格式化日期时间和标题的方法,显示如下: 日期:2017-03-03 时间:2017-03-0 11:11 标题:标题名称 <table id="tbList" style ...

  8. Swift中计算String的长度

        extension String {     var length: Int { return countElements(self) }  // Swift 1.1 } extension ...

  9. js 字符串长度截取

    <script> function cutstr(str, len) { var temp, icount = 0, patrn = /[^\x00-\xff]/, strre = &qu ...

  10. String 字符串递归截取字节字符串

    public static String idgui(String s,int num)throws Exception{ int changdu = s.getBytes("UTF-8&q ...

随机推荐

  1. html文字有光晕

    <style> .tb{ font-size:40px; filter:glow(color=pink,direction=); font-family:华文行楷; } </styl ...

  2. jquery升级到新版本报错[jQuery] Cannot read property ‘msie’ of undefined错误的解决方法(转)

    最近把一个项目的jQuery升级到最新版,发现有些页面报错Cannot read property 'msie' of undefined.上jQuery网站上搜了一下,原因是$.browser这个a ...

  3. curl http认证

    有些站点需要http认证.(apache认证:http://blog.csdn.net/zf213/article/details/4252592) 如果访问http://test:123789@xx ...

  4. /usr/lib64/python2.6/site-packages/pycurl.so: undefined symbol: CRYPTO_set_locking_callback

    [root@frontend01 yum.repos.d]# cd /etc/yum.repos.d;wget http://rpms.adiscon.com/v8-stable/rsyslog.re ...

  5. [LeetCode] 28. Implement strStr() 解题思路

    Implement strStr(). Returns the index of the first occurrence of needle in haystack, or -1 if needle ...

  6. POJ-2240

    Arbitrage Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 19063   Accepted: 8069 Descri ...

  7. mnist数据集转换bmp图片

    Mat格式mnist数据集下载地址:http://www.cs.nyu.edu/~roweis/data.html Matlab转换代码: load('mnist_all.mat'); type = ...

  8. ETL-Career RoadMap

    RoadMap: 1.Tester:sql的单体或批处理测试: 2. Application Developer 2.1 批处理手动工具(如何使用.如何调度批处理.如何生成批处理脚本): 2.2 批处 ...

  9. Swift学习笔记十六:协议

    Protocol(协议)用于统一方法和属性的名称,而不实现不论什么功能. 协议可以被类.枚举.结构体实现.满足协议要求的类,枚举,结构体被称为协议的遵循者. 遵循者须要提供协议指定的成员,如属性,方法 ...

  10. 使用awrextr.sql导出awr原始数据

    1.AWR原始数据与AWR报告的差别 AWR原始数据: 是oracle数据库mmon进程定期将统计量从内存转储至磁盘,并以结构化的形式存入若干张表组成自己主动工作负荷存储仓库(AutomaticWor ...