123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107 |
- <?php
- namespace app\expand\controller;
- use app\common\service\HelperService;
- use think\Validate;
- /**
- * 汉字转拼音接口
- * Class PinYin
- * @package app\expand\controller
- */
- class PinYin extends BaseAuth
- {
- private $_Account = null;
- public function __construct(){
- parent::__construct();
- $this->_Account = $this->getKey($this->_apiCode);
- //验证是否具有访问这个接口的权限
- if(!isset($this->_Account['PinYin'])){
- HelperService::returnJson(['code'=>400,'msg'=>'pinyin unauthorized access','data'=>[]]);
- }
- }
- /**
- * 将汉字翻译成拼音
- */
- public function transChinese(){
- $params = $this->_params;
- $rule = [
- 'old_string|待翻译参数'=>'require',
- 'is_first_word|是否仅需要首字母'=>'require'
- ];
- $validate = new Validate($rule);
- if(!$validate->check($params)){
- HelperService::returnJson(['code'=>400,'msg'=>$validate->getError(),'data'=>$params]);
- }
- $pinYin = $this->trans($params['old_string'],$this->pinYin());
-
- HelperService::returnJson(['code'=>200,'msg'=>'success','data'=>$pinYin]);
- }
- /**
- * 转义
- * @param type $oldStr
- * @param type $pinYinArr
- * @param type $isFirstWord 是否只需要第一个字母
- * @return string
- */
- private function trans($oldStr='',$pinYinArr=[],$isFirstWord=false) {
- $con = $this->mbStrSplit($oldStr);
- $str = '';
- for ($i=0;$i<count($con);$i++) {
- if (isset($pinYinArr[$con[$i]]) && $this->charCodeAt($con[$i]) > 200){
- $str .= $isFirstWord? strtoupper($pinYinArr[$con[$i]][0]):$pinYinArr[$con[$i]];
- }else {
- $str .= $isFirstWord?strtoupper($con[$i][0]):$con[$i];
- }
- $str .= $isFirstWord?'':' ';
- }
- return $str;
- }
- /**
- * 获取字符编码值
- * @param $char
- * @return null|number
- */
- private function charCodeAt($char)
- {
- if (mb_check_encoding($char, 'UTF-8'))
- {
- $ret = mb_convert_encoding($char, 'UTF-32BE', 'UTF-8');
- return hexdec(bin2hex($ret));
- }
- else
- {
- return null;
- }
- }
- /**
- * 拆分中英文
- * @param $str
- * @return array
- */
- private function mbStrSplit($str){
- return preg_split('/(?<!^)(?!$)/u', $str);
- }
- /**
- * 获取拼音大全
- * @return mixed
- */
- private function pinYin(){
- $pyDic = file_get_contents('pingyin.json');
- $returnArr = json_decode($pyDic,true);
- return $returnArr;
- }
- }
|