zoukankan      html  css  js  c++  java
  • 截取utf8字符串原理

     1 <?php
     2 //分析写在注释中
     3 class StringComponent{
     4     //大致原理就是一个一个字节去读,如果第一个字符ascll数值大于224连续三个组成一个字,如果大于192就是2个,否则就是一个字母或标点
     5     public static function cutString($sourceStr, $cutLength = 10, $extStr = '...'){
     6         $returnStr = ''; $i = 0; $n = 0; //$i用于指针,$n 统计字符长度
     7         $strLength = strlen($sourceStr);  //获取字符长度,注意这个不是字数的个数
     8         if ($strLength > $cutLength){   //判断参数合法
     9             while (($n < $cutLength) and ($i <= $strLength)){  //限定循环范围
    10                 $tempStr = substr($sourceStr, $i, 1);    //取出指针下一个字符
    11                 $ascnum = Ord($tempStr);    //取出ascll值
    12                 if ($ascnum >= 224){   //判断值的大小
    13                     $returnStr = $returnStr . substr($sourceStr, $i, 3);  //弹出取到的汉字到结果中
    14                     $i = $i+3;    //指针移动三个字符长度
    15                     $n++;  //字数统计+1
    16                 }elseif ($ascnum >= 192){ 
    17                     $returnStr=$returnStr.substr($sourceStr,$i,2);   //如上
    18                     $i=$i+2;
    19                     $n++;
    20                 }elseif ($ascnum >= 65 && $ascnum <= 90){
    21                     $returnStr = $returnStr.substr($sourceStr, $i, 1); //如上
    22                     $i = $i+1;
    23                     $n++;
    24                 }else{ 
    25                     $returnStr = $returnStr.substr($sourceStr, $i, 1);  //这里要说下,如果小于65就是标点字符了,算作0.5个字符
    26                     $i = $i+1;
    27                     $n = $n+0.5;
    28                 }
    29             }
    30             if ($strLength > $i){
    31                 $returnStr = $returnStr.$extStr;  //如果结果字符串小于长度那么,填上后缀标志
    32             }
    33             return $returnStr;
    34         }
    35         else
    36             return $sourceStr;   //如果截取长度大于总长,返回原来的字符串
    37     }
    38 }
    39 
    40 ?>
  • 相关阅读:
    poj 3662 Telephone Lines
    费马小定理证明
    CodeForces 1058 F Putting Boxes Together 树状数组,带权中位数
    共价大爷游长沙 lct 维护子树信息
    牛客暑假多校 F RIKKA with Line Graph
    牛客暑假多校 H Prefix sum
    HDU-6437 Videos
    模板汇总——AC自动机
    模板汇总——逆元
    模板汇总——LCT
  • 原文地址:https://www.cnblogs.com/linksgo2011/p/2866039.html
Copyright © 2011-2022 走看看