欢迎各位兄弟 发布技术文章
这里的技术是共享的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 | 对一段文字按照字数进行分割,因为文字中可能是中英文混合的,而php函数strlen只能计算出字串的字节数,于是自己实现了几个函数,分享下。例1,计算字符总长度。01 <?php 02 function ccStrLen($str) #计算中英文混合<a href="/"target="_blank" class="infotextkey">字符串</a>的长度 03 { 04 $ccLen=0; 05 $ascLen=strlen($str); 06 $ind=0; 07 $hasCC=ereg(”[xA1-xFE]“,$str); #判断是否有汉字 08 $hasAsc=ereg(”[x01-xA0]“,$str); #判断是否有ASCII字符 09 if($hasCC && !$hasAsc) #只有汉字的情况 10 return strlen($str)/2; 11 if(!$hasCC && $hasAsc) #只有Ascii字符的情况 12 return strlen($str); 13 for($ind=0;$ind<$ascLen;$ind++) 14 { 15 if(ord(substr($str,$ind,1))>0xa0) 16 { 17 $ccLen++; 18 $ind++; 19 } 20 else 21 { 22 $ccLen++; 23 } 24 } 25 return $ccLen; 26 } 27 ?> 例2,从左侧截取字符串。01 <?php 02 function ccStrLeft($str,$len) #从左边截取中英文混合字符串 03 { 04 $ascLen=strlen($str); if($ascLen<=$len) return $str; 05 $hasCC=ereg(”[xA1-xFE]“,$str); #同上 06 $hasAsc=ereg(”[x01-xA0]“,$str); 07 if(!$hasCC) return substr($str,0,$len); 08 if(!$hasAsc) 09 if($len & 0×01) #如果长度是奇数 10 return substr($str,0,$len+$len-2); 11 else 12 return substr($str,0,$len+$len); 13 $cind=0;$flag=0;$reallen=0;//实际取字节长 14 while($cind<$ascLen && $reallen<$len) 15 { //by www.jbxue.com 16 if(ord(substr($str,$cind,1))<0xA1){ //如果该字节为英文 则加一 17 $cind++; 18 }else{//否则 加2个字节 19 $cind+=2; 20 } 21 $reallen++; 22 } 23 return substr($str,0,$cind); 24 } 25 ?> 例3,把给定文字,按切割数量存入数组(适合短篇文字,长文章可没分隔一部分就直接处理一次)view sourceprint?01 <?php 02 function SplitContent($content,$smslen){ 03 $str_tmp=$content; 04 $arr_cont=array(); 05 $len_tmp=0; 06 $i=0;//分割绝对位置 07 while (strlen($str_tmp)>0){ 08 $str_tmp=ccStrLeft($str_tmp,$smslen); 09 array_push($arr_cont,$str_tmp); 10 $i+=strlen($str_tmp); 11 $str_tmp=substr($content,$i,strlen($content)); 12 } 13 return $arr_cont; 14 } //by www.jbxue.com 15 ?> 测试:1 <?php 2 $str=’a计算中英文混合1234字符串的长度abcd’; 3 echo $str.’的长度为:’.ccStrLen($str); 4 echo ‘’; 5 $smslen=3;//截取长度 6 print_r(SplitContent($str,$smslen)); 7 ?> |