Home  >  Article  >  Backend Development  >  Chinese interception without garbled characters (2 methods)

Chinese interception without garbled characters (2 methods)

WBOY
WBOYOriginal
2016-07-25 09:01:161058browse
Chinese interception without garbled characters (2 methods)
  1. //$str The string to be intercepted
  2. //$len The number of characters to be intercepted
  3. //$chars The number of characters that have been intercepted
  4. //$res The saved string
  5. // $chars stores the number of intercepted strings
  6. //$offset is the intercepted offset
  7. //$length is the number of bytes of the string
  8. //If $len>the number of characters in $str, it will cause a unnecessary while loop , ($offset<$length limit)
  9. function utf8sub($str,$len){
  10. if($len<=0){
  11. return ;
  12. }
  13. $res="";
  14. $offset=0;
  15. $ chars=0;
  16. $length=strlen($str);
  17. while($chars<$len && $offset<$length){
  18. $hign=decbin(ord(substr($str,$offset,1)) );
  19. if(strlen($hign)<8){
  20. $count=1;
  21. }elseif(substr($hign,0,3)=="110"){
  22. $count=2;
  23. }elseif (substr($hign,0,4)=="1110"){
  24. $count=3;
  25. }elseif(substr($hign,0,5)=="11110"){
  26. $count=4;
  27. }elseif(substr($hign,0,6)=="111110"){
  28. $count=5;
  29. }elseif(substr($hign,0,7)=="1111110"){
  30. $count=6 ;
  31. }
  32. $res.=substr($str,$offset,$count);
  33. $offset+=$count;
  34. $chars+=1;
  35. }
  36. return $res;
  37. }
  38. function utf8sub1($ str,$len){
  39. $chars=0;
  40. $res="";
  41. $offset=0;
  42. $length=strlen($str);
  43. while($chars<$len && $offset<$length) {
  44. $hign=decbin(ord(substr($str,$offset,1)));
  45. if(strlen($hign)<8){
  46. $count=1;
  47. }elseif($hign & "11100000 "=="11000000"){
  48. $count=2;
  49. }elseif($hign & "11110000"=="11100000"){
  50. $count=3;
  51. }elseif($hign & "11111000"==" 11110000"){
  52. $count=4;
  53. }elseif($hign & "11111100"=="11111000"){
  54. $count=5;
  55. }elseif($hign & "11111110"=="11111100"){
  56. $count=6;
  57. }
  58. $res.=substr($str,$offset,$count);
  59. $chars++;
  60. $offset+=$count;
  61. }
  62. return $res;
  63. }
  64. $a="中华ah人hdj";
  65. echo utf8sub($a,5);
  66. ?>
Copy code


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:php parses json arrayNext article:php parses json array