You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

65 lines
1.7 KiB

  1. <?php
  2. namespace Kuxin\Helper;
  3. use Kuxin\Config;
  4. /**
  5. * Class Pinyin
  6. *
  7. * @package Kuxin\Helper
  8. * @author Pakey <pakey@qq.com>
  9. */
  10. class Pinyin
  11. {
  12. protected static $data = null;
  13. /**
  14. * @return mixed
  15. */
  16. protected static function getdata()
  17. {
  18. if (self::$data === null) {
  19. $fp = fopen(__DIR__ . '/data/pinyin.dat', 'r') or exit('读取字典失败');
  20. while (!feof($fp)) {
  21. $line = trim(fgets($fp));
  22. self::$data[$line[0] . $line[1]] = substr($line, 3, strlen($line) - 3);
  23. }
  24. fclose($fp);
  25. }
  26. return self::$data;
  27. }
  28. /**
  29. * 转换成拼音
  30. *
  31. * @param string $str 待转换的字符串
  32. * @param bool $isfirst 是否只需要首字符
  33. * @param string $default 匹配不到默认显示字符
  34. * @return string
  35. */
  36. public static function change(string $str, $isfirst = null, $default = '_')
  37. {
  38. $str = iconv('UTF-8', 'GBK//ignore', $str);
  39. $isfirst = $isfirst === null ? (Config::get('pinyin.ucfirst', 1)) : $isfirst;
  40. $data = self::getdata();
  41. $restr = '';
  42. for ($i = 0, $j = strlen($str); $i < $j; $i++) {
  43. if (ord($str[$i]) > 0x80) {
  44. $c = $str[$i] . $str[$i + 1];
  45. ++$i;
  46. if (isset($data[$c])) {
  47. $restr .= $isfirst ? ucfirst($data[$c]) : $data[$c];
  48. } else {
  49. $restr .= $default;
  50. }
  51. } elseif (preg_match("/[\w\-]/i", $str[$i])) {
  52. $restr .= $str[$i];
  53. } else {
  54. $restr .= $default;
  55. }
  56. }
  57. return $restr;
  58. }
  59. }