使用php实现截取指定长度

yipeiwu_com5年前PHP代码库
PHP语言: 根据中文裁减字符串
复制代码 代码如下:

function cutstr($string,$length, $dot = ' ...') {
  if (strlen($string) <= $length) {
      return$string;
  }
  $pre = chr(1);
  $end = chr(1);
  $string = str_replace(array('&','"', '<', '>'),array($pre . '&'. $end, $pre . '"' . $end, $pre . '<' .$end, $pre . '>' . $end), $string);

  $strcut = '';
  if (strtolower(CHARSET) == 'utf-8'){
      $n = $tn =$noc = 0;
      while ($n< strlen($string)) {

         $t =ord($string[$n]);
         if ($t == 9 || $t == 10 || (32<= $t && $t <= 126)) {
            $tn = 1;
            $n++;
            $noc++;
         } elseif (194 <= $t&& $t <= 223) {
            $tn = 2;
            $n += 2;
            $noc += 2;
         } elseif (224 <= $t&& $t <= 239) {
            $tn = 3;
            $n += 3;
            $noc += 2;
         } elseif (240 <= $t&& $t <= 247) {
            $tn = 4;
            $n += 4;
            $noc += 2;
         } elseif (248 <= $t&& $t <= 251) {
            $tn = 5;
            $n += 5;
            $noc += 2;
         } elseif ($t == 252 || $t ==253) {
            $tn = 6;
            $n += 6;
            $noc += 2;
         } else {
            $n++;
         }

         if ($noc >= $length){
            break;
         }
     }
      if ($noc> $length) {
         $n -= $tn;
     }
      $strcut =substr($string, 0, $n);
  } else {
      for ($i =0; $i < $length; $i++) {
         $strcut .= ord($string[$i])> 127 ? $string[$i] . $string[++$i] : $string[$i];
     }
  }
  $strcut = str_replace(array($pre . '&' .$end, $pre . '"' . $end, $pre . '<' . $end, $pre . '>' .$end), array('&', '"','<', '>'), $strcut);

  $pos = strrpos($strcut, chr(1));
  if ($pos !== false) {
      $strcut =substr($strcut, 0, $pos);
  }
  return $strcut . $dot;
}

相关文章

php取整函数ceil,floo,round的用法及介绍

ceil  是向上进位得到一个值的函数;floor 是舍掉小数位得到一个值的函数;round 是用来四舍五入的函数 ceil定义和用法:ceil() 函数向上舍入为最接近的整数...

php错误提示failed to open stream: HTTP request failed!的完美解决方法

google或者baidu一下,好多这样的问题,解决的方法都是修改php.ini,把allow_url_fopen给启用,改成 allow_url_fopen = On 这样做可以解决某...

php处理斐波那契数列非递归方法

我自己构思了下,实际上程序来解决这个事情,就是一个偏移量的问题。首先看数列::1、1、2、3、5、8、13、21、34数列的下一个数是前2个数字之和,以此类推。 程序处理的话,实际上就是...

Discuz 模板引擎的封装类代码

主要功能说明 去掉了 Discuz 语言包的功能  移植 Discuz 模板中所有的功能  添加了自动更新缓存及生命周期功能&...

PHP服务端环境搭建的图文教程(分享)

PHP服务端环境搭建的图文教程(分享)

一、PHP服务端环境搭建 1.php 服务端环境 安装套件 xampp(apach+mysql+php解释器) F:\MyDoc文件(重要)\DL_学习\download重要资源\apa...