Laravel 将中文转换为拼音

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

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

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

在控制器里引入

use \Overtrue\Pinyin\Pinyin;
public function index(){
 $list = \App\Model\City::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

%s 个评论

要回复文章请先登录注册