引入第三方库(采用 composer)
composer require “overtrue/pinyin:~3.0”
引用文件: use Overtrue\Pinyin\Pinyin;
代码案例
if (!function_exists('pinyinMultitone')) {
function pinyinMultitone($str, $ret_format = 'all', $space = " ", $tone = false)
{
$pinyin = new Pinyin('Overtrue\Pinyin\MemoryFileDictLoader');
if ($tone == true) {
$pinyin = $pinyin->convert($str, PINYIN_UNICODE);
} else {
$pinyin = $pinyin->convert($str);
}
$rs = "";
foreach ($pinyin as $value) {
if ($ret_format == "first") {
$chr = mb_substr($value, 0, 1);
$rs .= $chr . $space;
} elseif ($ret_format == 'single') {
$chr = mb_substr($value, 0, 1);
return $chr;
} else {
$rs .= $value . $space;
}
}
return rtrim($rs, ' ');
}
}
调用案例
$initial = pinyinMultitone('屖屗屘', 'all');
|