当前位置:首页 > PHP教程 > php函数 > 列表

php 截取中文字符串实现程序

发布:smiling 来源: PHP粉丝网  添加日期:2014-07-27 15:07:05 浏览: 评论:0 

在php中我们截取字符串可以使用自带的函数,但是自带的函数不支持中文截取,如果需要截取中文字符串我们需要现做一些操作,下面我来给各位朋友介绍.

针对GB2312的代码,代码如下:

  1. //$str是要截取的字符串 
  2. //$start是要截取的字符的开始位置 
  3. //$len是指要截取的字符长度 
  4. function sub_str($str$start$len) { 
  5.         $tmpstr = ""
  6.         $strlen = $start + $len
  7.         for($i = 0; $i < $strlen$i++) { 
  8.             if(ord(substr($str$i, 1)) > 0xa0) { 
  9.                 $tmpstr .= substr($str$i, 2); 
  10.                 $i++; 
  11.             } else 
  12.                 $tmpstr .= substr($str$i, 1); 
  13.         } 
  14.         return $tmpstr."..."

针对uft8,代码如下:

  1. <?php 
  2. //截取utf8字符串 
  3. function utf8substr($str$from$len
  4.     return preg_replace('#^(?:[x00-x7f]|[xc0-xff][x80-xbf]+){0,'.$from.'}'
  5.                        '((?:[x00-x7f]|[xc0-xff][x80-xbf]+){0,'.$len.'}).*#s'
  6.                        '$1',$str); 
  7. ?> 

上面的方法肯定不实用,因为我希望可以自动识别支持任何编码的字符串截取,后来找到一个还算可以的分享给各位朋友,代码如下:

  1. <?php 
  2. /** 
  3.  * @package     BugFree 
  4.  * @version     $Id: FunctionsMain.inc.php,v 1.32 2005/09/24 11:38:37 wwccss Exp $ 
  5.  * 
  6.  * 
  7.  * Return part of a string(Enhance the function substr()) 
  8.  * 
  9.  * @author                  Chunsheng Wang <wwccss@263.net> 
  10.  * @param string  $String  the string to cut. 
  11.  * @param int     $Length  the length of returned string. 
  12.  * @param booble  $Append  whether append "...": false|true 
  13.  * @return string           the cutted string. 
  14.  */ 
  15. function sysSubStr($String,$Length,$Append = false) 
  16.     if (strlen($String) < = $Length ) 
  17.     { 
  18.         return $String
  19.     } 
  20.     else 
  21.     { 
  22.         $I = 0; 
  23.         while ($I < $Length
  24.         { 
  25.             $StringTMP = substr($String,$I,1); 
  26.             if ( ord($StringTMP) >=224 ) 
  27.             { 
  28.                 $StringTMP = substr($String,$I,3); 
  29.                 $I = $I + 3; 
  30.             } 
  31.             elseif( ord($StringTMP) >=192 ) 
  32.             { 
  33.                 $StringTMP = substr($String,$I,2); 
  34.                 $I = $I + 2; 
  35.             } 
  36.             else 
  37.             { 
  38.                 $I = $I + 1; 
  39.             } 
  40.             $StringLast[] = $StringTMP
  41.         } 
  42.         $StringLast = implode("",$StringLast); 
  43.         if($Append
  44.         { 
  45.             $StringLast .= "..."
  46.         } 
  47.         return $StringLast
  48.     } 
  49. $String = "www.phpfensi.com 走在中国自动化测试的前沿"
  50. $Length = "18"
  51. $Append = false; 
  52. echo sysSubStr($String,$Length,$Append); 
  53. ?> 

Tags: php 截取中文字符串

分享到: