好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

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

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

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

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

//$str是要截取的字符串   //$start是要截取的字符的开始位置   //$len是指要截取的字符长度   function  sub_str( $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 . "..." ;  } 

针对uft8,代码如下:

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

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

<?php  /**    * @package     BugFree    * @version     $Id: FunctionsMain.inc.php,v 1.32 2005/09/24 11:38:37 wwccss Exp $    *    *    * Return part of a string(Enhance the function substr())    *    * @author                  Chunsheng Wang <wwccss@263.net>    * @param string  $String  the string to cut.    * @param int     $Length  the length of returned string.    * @param booble  $Append  whether append "...": false|true    * @return string           the cutted string.    */   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  =  "HdhCmsTestphpfensi测试数据 走在中国自动化测试的前沿" ;  $Length  =  "18" ;  $Append  = false;  echo  sysSubStr( $String , $Length , $Append );  ?> 

查看更多关于php 截取中文字符串实现程序 - php函数的详细内容...

  阅读:42次