PHP gets Chinese string first letter

Source: Internet
Author: User
Encountered a Chinese string sorting problem, to get the first letter of Chinese, the program can get the first letter of any string.
The principle is that according to the gb2312 encoding is sorted by pinyin. Unfamiliar with gb2312, you can look at the coding method.
Source: http://www.phpman.cn
  1. $limit =array (//gb2312 pinyin sort
  2. Array (45217,45252),//a
  3. Array (45253,45760),//b
  4. Array (45761,46317),//c
  5. Array (46318,46825),//d
  6. Array (46826,47009),//e
  7. Array (47010,47296),//f
  8. Array (47297,47613),//g
  9. Array (47614,48118),//h
  10. Array (0,0),//i
  11. Array (48119,49061),//j
  12. Array (49062,49323),//k
  13. Array (49324,49895),//l
  14. Array (49896,50370),//m
  15. Array (50371,50613),//n
  16. Array (50614,50621),//o
  17. Array (50622,50905),//p
  18. Array (50906,51386),//q
  19. Array (51387,51445),//r
  20. Array (51446,52217),//s
  21. Array (52218,52697),//t
  22. Array (0,0),//u
  23. Array (0,0),//v
  24. Array (52698,52979),//w
  25. Array (52980,53688),//x
  26. Array (53689,54480),//y
  27. Array (54481,55289),//z
  28. );
  29. $str = "A: This is a test program 1";
  30. $str = Iconv ("UTF-8", "gb2312", $str);
  31. echo $str. "
    ";
  32. $i = 0;
  33. while ($i
  34. $tmp =bin2hex (substr ($str, $i, 1));
  35. if ($tmp >= ' B0 ') {//start of Kanji
  36. $t =getletter (Hexdec (Bin2Hex (substr ($str, $i, 2)));
  37. printf ("%c", $t ==-1? ' * ': $t);
  38. $i +=2;
  39. }
  40. else{
  41. printf ("%s", substr ($str, $i, 1));
  42. $i + +;
  43. }
  44. }
  45. function Getletter ($num) {
  46. Global $limit;
  47. $char _index=65;
  48. foreach ($limit as $k = = $v) {
  49. if ($num >= $v [0] && $num <= $v [1]) {
  50. $char _index+= $k;
  51. return $char _index;
  52. }
  53. }
  54. return-1;
  55. }
  56. ?>
Copy Code
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.