Home  >  Article  >  Backend Development  >  PHP gets the first character pinyin letter of Chinese string

PHP gets the first character pinyin letter of Chinese string

WBOY
WBOYOriginal
2016-07-25 08:42:14958browse
  1. $str="这是一个测试程序1";
  2. echo getFirstCharCode($str);
  3. function getFirstCharCode($str){
  4. $str= iconv("UTF-8","gb2312", $str);
  5. $targetChar='*';
  6. $i=0;
  7. while($i $tmp=bin2hex(substr($str,$i,1));
  8. if($tmp>='B0'){ //汉字的开始
  9. $t=getLetter(hexdec(bin2hex(substr($str,$i,2))));
  10. $targetChar=$t==-1 ? '*' : $t ;
  11. //printf("%c",$t==-1 ? '*' : $t );
  12. break;
  13. //$i+=2;
  14. }
  15. else{
  16. $targetChar=substr($str,$i,1);
  17. break;
  18. //printf("%s",substr($str,$i,1));
  19. //$i++;
  20. }
  21. }
  22. if(is_numeric($targetChar)){
  23. return chr($targetChar);
  24. }
  25. else{
  26. return $targetChar;
  27. }
  28. }
  29. function getLetter($num){
  30. $limit=array( //gb2312 拼音排序
  31. array(45217,45252), //A
  32. array(45253,45760), //B
  33. array(45761,46317), //C
  34. array(46318,46825), //D
  35. array(46826,47009), //E
  36. array(47010,47296), //F
  37. array(47297,47613), //G
  38. array(47614,48118), //H
  39. array(0,0), //I
  40. array(48119,49061), //J
  41. array(49062,49323), //K
  42. array(49324,49895), //L
  43. array(49896,50370), //M
  44. array(50371,50613), //N
  45. array(50614,50621), //O
  46. array(50622,50905), //P
  47. array(50906,51386), //Q
  48. array(51387,51445), //R
  49. array(51446,52217), //S
  50. array(52218,52697), //T
  51. array(0,0), //U
  52. array(0,0), //V
  53. array(52698,52979), //W
  54. array(52980,53688), //X
  55. array(53689,54480), //Y
  56. array(54481,55289), //Z
  57. );
  58. $char_index=65;
  59. foreach($limit as $k=>$v){
  60. if($num>=$v[0] && $num<=$v[1]){
  61. $char_index+=$k;
  62. return $char_index;
  63. }
  64. }
  65. return -1;
  66. }
复制代码

php


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