今天产品下了新需求,要给系统加双语切换,在做到国家城市库映射的时候,我在度娘上找了个双语版的数据库,可是系统已经在生产半年了,直接换表肯定是要背锅的,转念一想,要是能把城市信息直接替换为拼音不就行了,在此将操作步骤整理下来。

首先需要安装一下扩展overtrue/pinyin,执行命令,我的框架是6.0,安装的扩展版本是^4.0

composer require overtrue/pinyin -vvv
GitHub地址:https://github.com/overtrue/pinyin

在控制器里引入

use OvertruePinyinPinyin;
public function index(){
    $list = AppModelCity::whereNull('name_en')->get(); // 取出没有英文的数据
    $pinyin = new Pinyin();
    foreach ($list as $item){
        $arr = $pinyin->permalink($item['name'],'');  // 中文转拼音
        $en = str_replace(['qu','xian','shi'],'',$en);  //替换掉区县市后缀
        $item->name_en = ucfirst($en);
        $item->save();
    }
}

overtrue/pinyin扩展的其他实现:

  1. 汉字转成拼音
$pinyin->convert('保护地球,热爱和平');

//['bao','hu','dd','qiu','re','ai','he','ping']
  1. 汉字转成带音调的拼音
$pinyin->convert('保护地球,热爱和平', PINYIN_TONE);

//['bǎo','hù','dì','qiú','rè','ài','hé','píng']
  1. 汉字转成拼音字符串
$pinyin->permalink('保护地球,热爱和平');

//baohudiqiureaiheping
  1. 汉字转成拼音首字母字符串
$pinyin->abbr('保护地球,热爱和平');
//bhdqrahp

$pinyin->abbr('保护地球,热爱和平',',');
//b,h,d,q,r,a,h,p
  1. 转成拼音时包含符号
$pinyin->sentence('保护地球,热爱和平');
//bao hu di qiu, re ai he ping

$pinyin->sentence('保护地球,热爱和平','-');
//bao-hu-di-qiu,-re-ai-he-ping
  1. 转换带多音字的姓名
$pinyin->name('仇笑痴');
//['qiu','xiao','chi']
内容来源于网络如有侵权请私信删除

文章来源: 博客园

原文链接: https://www.cnblogs.com/iwillrich/p/16379103.html

你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!