PHP & 技术 04 Jan 2005 11:05 am

utf-8字符串截取函数

(转自村子sunggsun)

  1. /**
  2. * utf-8编码字符串截取函数
  3. * @param string $string 要截取的字符串
  4. * @param int $start 起始位置
  5. * @param int $length 截取长度
  6. * @param author sunggsun
  7. * @date: 2004-12-3
  8. */
  9.  
  10.  
  11.  
  12. function utf8_substr($string, $start, $length=-1) {
  13.     switch ($length) {
  14.      case 0:
  15.             return '';
  16.         case -1:
  17.             return $string;       
  18.     }
  19.     preg_match_all("/([x80-xff]{0,3}|[^x80-xff]?)/is", $string, $arr);
  20.     $rs = array();
  21.     foreach($arr[0] as $key=>$value) {
  22.         if (trim($value) != '') {
  23.             $rs[] = $value;
  24.         }
  25.     }
  26.     $end = $start+$length;
  27.     $len = 0;
  28.     $str = '';
  29.     foreach ($rs as $key=>$value) {
  30.         $l = $len+strlen($value);
  31.         if ($l >= $start && !isset($s)) {
  32.             $s = $len;
  33.         }
  34.         if ($l >= $end && !isset($e)) {
  35.             $e = $l;
  36.             break;
  37.         }
  38.         $len = $l;
  39.     }
  40.     $l = $e - $s;
  41.     return substr(implode('', $rs), $s, $l);
  42. } 
  43. $str = "这a是3一b个UTF-8字符串*&^……%¥";
  44. echo $str . "
  45. rn";
  46.  
  47. $len = strlen($str);
  48. for ($i=0; $i<$len; $i++) {
  49.     for ($n=0; $n<=$len-$i; $n++) {
  50.         if ($i < 10) {
  51.             $a = " " . $i;
  52.         }
  53.         if ($n < 10) {
  54.             $b = " " . $n;
  55.         }
  56.         echo $a . "," . $b . ":" . utf8_substr($str, $i, $n) . "
  57. rn";
  58.     }
  59. }
  60. ?>

Trackback This Post | Subscribe to the comments through RSS Feed

Leave a Reply