字符串示例:一百三十二,转成132。
PHP中文数字转阿拉伯数字:一
/** * 中文数字替换阿拉伯数字 */ function SwitchChnNumber( $time ) { if ( ! empty( $time ) ) { $replaceValueC = [ "零" => 0, "一" => 1, "二" => 2, "两" => 2, "三" => 3, "四" => 4, "五" => 5, "六" => 6, "七" => 7, "八" => 8, "九" => 9, "十" => '0', "百" => '00', "千" => '000', "万" => '0000', ]; //拆分含有中文的字符串 $arrTime = preg_split( '/(?<!^)(?!$)/u', $time ); foreach ( $arrTime as $key => $value ) { if ( isset( $replaceValueC[ $value ] ) && $replaceValueC[ $value ] != '' ) { $arrTime[ $key ] = $replaceValueC[ $value ]; } else { $arrTime[ $key ] = $value; } } return implode( "", $arrTime ); } else { return $time; } }
PHP中文数字转阿拉伯数字:二
function ch2num($str){ //单位数组用于循环遍历,单位顺序从大到小 $c = [ '万亿'=>1000000000000, '亿' => 100000000, '万' => 10000, ]; //中文替换数字规则,零没什么卵用;所以去掉 $b = [ '一' =>1, '二' =>2, '三' =>3, '四' =>4, '五' =>5, '六' =>6, '七' =>7, '八' =>8, '九' =>9, '零' =>'', ]; //替换数字 $str = str_replace(array_keys($b), array_values($b), $str); //结果 7百7十8万亿4千7百2十亿7千5百7十万4千4百8十 //如果字符串以十开头,前边加1 if(mb_strpos($str, '十' ,0 ,'utf-8') === 0) $str = '1'.$str; //初始化一个数组 $arr[] = array( 'str' => $str, //字符串 'unit' => 1, //单位 ); //将字符串按单位切分 foreach ($c as $key => $value) { $brr = []; foreach ($arr as $item) { if(strpos($item['str'], $key)){ $sun = explode($key, $item['str'],2); $brr[] = [ 'str' => $sun[0], 'unit' => $value, ]; $brr[] = [ 'str' => $sun[1], 'unit' => $item['unit'], ]; }else{ $brr[] = $item; } } $arr = $brr; } //遍历求和 $sum = 0; foreach ($arr as $item) { $sum += getNum($item['str'],$item['unit']); } return $sum; } //将分组后的字符串转化成数字,并乘以单位 function getNum($str,$st){ //倍数 $a = [ '千'=>1000, '百'=>100, '十'=>10 ]; //开始值 $num = 0; //当前值所在位数 $step = 1; //单位 $un = 1; $arr = preg_split('/(?<!^)(?!$)/u', $str); while (count($arr)) { $m = array_pop($arr); //如果是位数;更新倍数 if(!empty($a[$m])){ $step = $a[$m]; } if(is_numeric($m)){ $num += $m * $step; } } return $num * $st; }