疯狂编程网

  • 首页
  • 后端
    • GOLANG
    • PHP
  • 前端
  • 客户端
  • 服务器
  • AIGC
  • 开发工具
  • 代码人生
  • 关于本站
    • 联系我们
    • 免责声明
  1. 首页
  2. 后端
  3. PHP
  4. 正文

Laravel 将中文转换为拼音

2023年5月10日 252点热度 0人点赞 0条评论

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

首先需要安装一下扩展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']
标签: php
最后更新:2023年5月10日

大明

靠写代码养家的开发者。

点赞
< 上一篇
下一篇 >

文章评论

razz evil exclaim smile redface biggrin eek confused idea lol mad twisted rolleyes wink cool arrow neutral cry mrgreen drooling persevering
取消回复

COPYRIGHT © 2023 疯狂编程网. ALL RIGHTS RESERVED.

京ICP备2022013580号-1