使用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获取远程图片的两种 CURL方式和sockets方式获取远程图片

方式1:sockets 复制代码 代码如下: $a = "/zb_users/upload/202003/hyvt1amvtlt.jpg"; $local = 'socket1.gif'...

php设置允许大文件上传示例代码

用Nginx做为代理服务器, 后端为 apache2. 设置允许上传最大为100M的文件. 1. Nginx配置: http { ...... client_max_body_size...

PHP array操作10个小技巧分享

1、向array中添加元素 php是一个弱类型语言。因此不必象c语言那样为php array声明长度。向其中添加元素的过程也是声明和初始化的过程。 复制代码 代码如下: $capital...

启用OPCache提高PHP程序性能的方法

启用OPCache提高PHP程序性能的方法

说明 PHP 5.5+版本以上的,可以使用PHP自带的opcache开启性能加速(默认是关闭的)。对于PHP 5.5以下版本的,需要使用APC加速,这里不说明,可以自行上网搜索PHP A...

php使用curl详细解析及问题汇总

七夕啦,作为开发,妹子没得撩就“撩”下服务器吧,妹子有得撩的同学那就左拥妹子右抱服务器吧,况且妹子是要礼物的,服务器又不用。好啦,长话短说再长说,祭出今天的工具——CURL(Client...