提供一款大家可能用得比較少的把數字轉換成漢字的php代碼,有需要的朋友可以參考一下。
代碼如下
復制代碼
//將數字轉換為漢字,比如1210轉換為一千二百一十
$num = "842105580";//九位數
function del0($num) //去掉數字段前面的0
{
return "".intval($num);
}
function n2c($x) //單個數字變漢字
{
$arr_n = array("零","一","二","三","四","五","六","七","八","九","十");
return $arr_n[$x];
}
function num_r($abcd) //讀取數值(4位)
{
$arr= array();
$str = ""; //讀取後的漢字數值
$flag = 0; //該位是否為零
$flag_end = 1; //是否以“零”結尾
$size_r = strlen($abcd);
for($i=0; $i<$size_r; $i++)
{
$arr[$i] = $abcd{$i};
}
$arrlen = count($arr);
for($j=0; $j<$arrlen; $j++)
{
$ch = n2c($arr[$arrlen-1-$j]); //從後向前轉漢字
echo $ch;
echo "";
if($ch == "零" && $flag == 0){ //如果是第一個零
$flag = 1; //該位為零
$str = $ch.$str; //加入漢字數值字符串
continue;
}elseif($ch == "零"){ //如果不是第一個零了
continue;
}
$flag = 0; //該位不是零
switch($j) {
case 0: $str = $ch; $flag_end = 0; break; //第一位(末尾),沒有以“零”結尾
case 1: $str = $ch."十".$str; break; //第二位
case 2: $str = $ch."百".$str; break; //第三位
case 3: $str = $ch."千".$str; break; //第四位
}
}
if($flag_end == 1) //如果以“零”結尾
{
mb_internal_encoding("UTF-8");
$str = mb_substr($str, 0, mb_strlen($str)-1); //把“零”去掉
}
return $str;
}
function num2ch($num) //整體讀取轉換
{
$num_real = del0($num);//去掉前面的“0”
$numlen = strlen($num_real);
echo "numlen=".$numlen."";
if($numlen >= 9)//如果滿九位,讀取“億”位
{
$y=substr($num_real, -9, 1);
//echo $y;
$wsbq = substr($num_real, -8, 4);
$gsbq = substr($num_real, -4);
$a = num_r(del0($gsbq));
$b = num_r(del0($wsbq))."萬";
$c = num_r(del0($y))."億";
}elseif($numlen <= 8 && $numlen >= 5) //如果大於等於“萬”
{
$wsbq = substr($num_real, 0, $numlen-4);
$gsbq = substr($num_real, -4);
$a = num_r(del0($gsbq));
$b = num_r(del0($wsbq))."萬";
$c="";
}elseif($numlen <= 4) //如果小於等於“千”
{
$gsbq = substr( $num_real, -$numlen);
$a = num_r(del0($gsbq));
$b="";
$c="";
}
$ch_num = $c.$b.$a;
return $ch_num;
}
echo $num.""; //數字
echo num2ch($num); //漢字
echo "";
echo num2ch("1240");