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.
 
 
 
 

71 lines
2.2 KiB

  1. <?php
  2. namespace Kuxin\Helper;
  3. class OpenCC
  4. {
  5. protected static $data = null;
  6. protected static function getData($key = '')
  7. {
  8. if (self::$data === null) {
  9. $data = file_get_contents(__DIR__ . "/data/opencc.dat", 'r') or exit('读取字典失败');
  10. if (empty(self::$data = Json::decode($data)))
  11. exit('解析字典失败');
  12. }
  13. return $key ? Arr::get(self::$data, $key) : self::$data;
  14. }
  15. public static function change(string $content, $type = 'from')
  16. {
  17. if ($type == 'from') {
  18. return self::fromutf8($content);
  19. } else {
  20. return self::toutf8($content);
  21. }
  22. }
  23. public static function fromutf8(string $content)
  24. {
  25. static $_word;
  26. if (empty($_word)) {
  27. $tcData = self::getData('character.tc');
  28. $scData = self::getData('character.sc');
  29. $length = mb_strlen($tcData);
  30. for ($i = 0; $i < $length; $i++) {
  31. $_word[mb_substr($scData, $i, 1)] = mb_substr($tcData, $i, 1);
  32. }
  33. }
  34. //基础单字替换
  35. $resStr = $content;
  36. //地区用词替换
  37. $resStr = strtr($resStr, self::getData('phrases.base'));
  38. $resStr = strtr($resStr, self::getData('phrases.tw_it'));
  39. $resStr = strtr($resStr, self::getData('phrases.tw_other'));
  40. $resStr = strtr($resStr, $_word);
  41. return $resStr;
  42. }
  43. public static function toutf8(string $content)
  44. {
  45. static $_word;
  46. if (empty($_word)) {
  47. $tcData = self::getData('character.tc');
  48. $scData = self::getData('character.sc');
  49. $length = mb_strlen($tcData);
  50. for ($i = 0; $i < $length; $i++) {
  51. $_word[mb_substr($tcData, $i, 1)] = mb_substr($scData, $i, 1);
  52. }
  53. }
  54. //基础单字替换
  55. $resStr = $content;
  56. //地区用词替换
  57. $resStr = strtr($resStr, array_flip(self::getData('phrases.base')));
  58. $resStr = strtr($resStr, array_flip(self::getData('phrases.tw_it')));
  59. $resStr = strtr($resStr, array_flip(self::getData('phrases.tw_other')));
  60. $resStr = strtr($resStr, $_word);
  61. return $resStr;
  62. }
  63. }