1、阿拉伯數字轉為中文數字(1-1億範圍)123=>一百二十三)
function numToWord($num){
$chiNum = array('零', '一', '二', '三', '四', '五', '六', '七', '八', '九');
$chiUni = array('','十', '百', '千', '萬', '十', '百', '千', '億');
$chiStr = '';
$num_str = (string)$num;
$count = strlen($num_str);
$last_flag = true; //上一個 是否為0
$zero_flag = true; //是否第一個
$temp_num = null; //臨時數字
$chiStr = '';//拼接結果
if ($count == 2) {//兩位數
$temp_num = $num_str[0];
$chiStr = $temp_num == 1 ? $chiUni[1] : $chiNum[$temp_num].$chiUni[1];
$temp_num = $num_str[1];
$chiStr .= $temp_num == 0 ? '' : $chiNum[$temp_num];
}else if($count > 2){
$index = 0;
for ($i=$count-1; $i >= 0 ; $i--) {
$temp_num = $num_str[$i];
if ($temp_num == 0) {
if (!$zero_flag && !$last_flag ) {
$chiStr = $chiNum[$temp_num]. $chiStr;
$last_flag = true;
}
if($index == 4 && $temp_num == 0){
$chiStr = "萬".$chiStr;
}
}else{
if($i == 0 && $temp_num == 1 && $index == 1 && $index == 5){
$chiStr = $chiUni[$index%9] .$chiStr;
}else{
$chiStr = $chiNum[$temp_num].$chiUni[$index%9] .$chiStr;
}
$zero_flag = false;
$last_flag = false;
}
$index ++;
}
}else{
$chiStr = $chiNum[$num_str[0]];
}
return $chiStr;
}
2、把中文數字轉為阿拉伯數字
function cn2num($string){
if(is_numeric($string)){
return $string;
}
// '仟' => '千','佰' => '百','拾' => '十',
$string = str_replace('仟', '千', $string);
$string = str_replace('佰', '百', $string);
$string = str_replace('拾', '十', $string);
$num = 0;
$wan = explode('萬', $string);
if (count($wan) > 1) {
$num += cn2num($wan[0]) * 10000;
$string = $wan[1];
}
$qian = explode('千', $string);
if (count($qian) > 1) {
$num += cn2num($qian[0]) * 1000;
$string = $qian[1];
}
$bai = explode('百', $string);
if (count($bai) > 1) {
$num += cn2num($bai[0]) * 100;
$string = $bai[1];
}
$shi = explode('十', $string);
if (count($shi) > 1) {
$num += cn2num($shi[0] ? $shi[0] : '一') * 10;
$string = $shi[1] ? $shi[1] : '零';
}
$ling = explode('零', $string);
if (count($ling) > 1) {
$string = $ling[1];
}
$d = array(
'一' => '1','二' => '2','三' => '3','四' => '4','五' => '5','六' => '6','七' => '7','八' => '8','九' => '9',
'壹' => '1','貳' => '2','叄' => '3','肆' => '4','伍' => '5','陸' => '6','柒' => '7','捌' => '8','玖' => '9',
'零' => 0, '0' => 0, 'O' => 0, 'o' => 0,
'兩' => 2
);
return $num + @$d[$string];
}
這是我建立的PHP技術討論群,歡迎各位大佬入群
本作品採用《CC 協議》,轉載必須註明作者和本文連結
我的部落格:www.zhangkaixing.com