截取字符,中英混合无乱码。 一个汉字当作一个字符
2015-08-13 09:57
435 查看
<?php //PHP中英文截取无乱码 header('Content_type=text/php;charset=UTF-8'); $str = '浙江zju大学'; //关键在于判断往后截多少个字节上,这是这个函数的核心 //此函数是用客串来判断的,效率不高 //位运算效果会更好 //110x xxxx && 1110 0000 -> 1100 0000 //1110 xxxx && 1111 0000 -> 1110 0000 //位运算时不受英文字符最高位为0的影响,只是在转成字符串才受到影响 function utf8sub($str,$len){ if($len<0){ return ''; } $res = ''; $offset = 0; $chars = 0; $count = 0; $length = strlen($str);//待截取字符串的字节数 while($chars<$len && $offset<$length){ $high = decbin(ord(substr($str,$offset,1)));//先截取客串的一个字节,substr按字节进行截取 //重要突破,已经能够判断高位字节 if(strlen($high)<8){//英文字符ascii编码长度为7,通过长度小于8来判断 $count = 1; // echo 'hello,I am in','<br>'; }elseif (substr($high,0,3) == '110') { $count = 2; //取两个字节的长度 }elseif (substr($high,0,4) == '1110') { $count = 3; //取三个字节的长度 }elseif (substr($high,0,5) == '11110') { $count = 4; }elseif (substr($high,0,6) == '111110') { $count = 5; }elseif(substr($high,0,7)=='1111110'){ $count = 6; } $res .= substr($str,$offset,$count); $chars +=1; $offset += $count; } return $res; } echo utf8sub($str,1),'<br>'; echo utf8sub($str,10),'<br>'; ?>
相关文章推荐
- Qt Quick 版本
- 九度 Online Judge 算法 刷题 题目1018:统计同成绩学生人数
- 造轮子之商业下拉菜单
- 博弈论之Nim问题
- html中submit和button的区别(总结)
- 谈谈 React.js 的核心入门知识
- win10正式版开机登录密码如何正确取消?
- 大数乘法 poj 2389 ||大数乘法 hdu1402 FFT模板
- 马拉松成绩和体重的关系
- lucene的域存储选项和索引选项
- 连接池 druid(阿里巴巴的框架)
- C++实现线程池
- 栈内存和堆内存的一点小结 《程序员的自我修养》·笔记
- Android中MVP
- [leetcode-131]Palindrome Partitioning(java)
- 【hdoj 4315】Climbing the Hill
- [CodeForces 300D Painting Square]DP
- 腾讯面试题目之一
- iOS 9 之New UIKit for International User Interfaces
- Mybatis拦截器介绍