推荐4-ChineseUtil v1.1.2 发布,PHP 中文工具包

2019-09-02 16:34:25 浏览数 (1)

Github: https://github.com/Yurunsoft/ChineseUtil

v1.1.2 更新内容

* 修复一系列因 PHP 版本、环境、模式,导致的转换差异问题

* 测试用例加持,保证类库稳定性

使用说明

Composer 直接安装

composer require yurunsoft/chinese-util

Composer 项目配置引入

代码语言:javascript复制
"require": {
    "yurunsoft/chinese-util" : "~1.0"
}

功能

汉字转拼音

代码语言:javascript复制
use YurunUtilChinese;
use YurunUtilChinesePinyin;
$string = '恭喜發財!123';
echo $string, PHP_EOL;

echo '全拼:', PHP_EOL;
var_dump(Chinese::toPinyin($string, Pinyin::CONVERT_MODE_PINYIN));

echo '首字母:', PHP_EOL;
var_dump(Chinese::toPinyin($string, Pinyin::CONVERT_MODE_PINYIN_FIRST));

echo '读音:', PHP_EOL;
var_dump(Chinese::toPinyin($string, Pinyin::CONVERT_MODE_PINYIN_SOUND));

echo '读音数字:', PHP_EOL;
var_dump(Chinese::toPinyin($string, Pinyin::CONVERT_MODE_PINYIN_SOUND_NUMBER));

echo '自选返回格式   以文本格式返回   自定义分隔符:', PHP_EOL;
var_dump(Chinese::toPinyin($string, Pinyin::CONVERT_MODE_PINYIN | Pinyin::CONVERT_MODE_PINYIN_SOUND_NUMBER, ' '));

echo '所有结果:', PHP_EOL;
var_dump(Chinese::toPinyin($string));

echo '不分割无拼音字符:', PHP_EOL;
var_dump(Chinese::toPinyin($string, Pinyin::CONVERT_MODE_PINYIN, ' ', false));

// 结果太长,请自行运行代码查看

拼音分词

代码语言:javascript复制
use YurunUtilChinese;
$string2 = 'xianggang';
echo '"', $string2, '"的分词结果:', PHP_EOL;
var_dump(Chinese::splitPinyin($string2));
/**
输出结果:
"xianggang"的分词结果:
array(2) {
  [0]=>
  string(12) "xi ang gang "
  [1]=>
  string(11) "xiang gang "
}
 * /

简繁互转

代码语言:javascript复制
use YurunUtilChinese;
$string3 = '中华人民共和国!恭喜發財!';
echo '"', $string3, '"的简体转换:', PHP_EOL;
var_dump(Chinese::toSimplified($string3));
echo '"', $string3, '"的繁体转换:', PHP_EOL;
var_dump(Chinese::toTraditional($string3));
/**
输出结果:
"中华人民共和国!恭喜發財!"的简体转换:
array(1) {
  [0]=>
  string(39) "中华人民共和国!恭喜发财!"
}
"中华人民共和国!恭喜發財!"的繁体转换:
array(1) {
  [0]=>
  string(39) "中華人民共和國!恭喜發財!"
}
 * /

数字转换

代码语言:javascript复制
use YurunUtilChineseNumber;
function test($number)
{
    $chinese = Number::toChinese($number, [
        'tenMin'    =>  true, // “一十二” => “十二”
    ]);
    $afterNumber = Number::toNumber($chinese);
    echo $number, '=>', $chinese, '=>', $afterNumber, '=>', 0 === bccomp($number, $afterNumber, 20) ? 'true' : 'false', PHP_EOL;
}

test(1.234);
test(-1234567890.666);
test(pi());
/**
输出结果:
1.234=>一点二三四=>1.234=>true
-1234567890.666=>负十二亿三千四百五十六万七千八百九十点六六六=>-1234567890.666=>true
3.1415926535898=>三点一四一五九二六五三五八九八=>3.1415926535898=>true
 */

金额数字转换

代码语言:javascript复制
use YurunUtilChineseMoney;
function test($number)
{
    $chinese = Money::toChinese($number, [
        'tenMin'    =>  true, // “一十二” => “十二”
    ]);
    $afterMoney = Money::toNumber($chinese);
    echo $number, '=>', $chinese, '=>', $afterMoney, '=>', 0 === bccomp($number, $afterMoney) ? 'true' : 'false', PHP_EOL;
}

test(1.234);
test(-1234567890.666);
/**
输出结果:
1.234=>壹圆贰角叁分肆厘=>1.234=>true
-1234567890.666=>负壹拾贰亿叁仟肆佰伍拾陆万柒仟捌佰玖拾圆陆角陆分陆厘=>-1234567890.666=>true
 */

0 人点赞