人民币数字和中文汉字转换

在PHP中,将人民币的中文汉字金额转换为数字,或者将数字转换为人民币的中文汉字金额,通常需要自定义一些函数来实现这一转换过程。下面分别给出这两个转换的示例代码。

数字转人民币中文汉字

php 复制代码
function numberToChinese($num) {  
    $cnNums = array('零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖');  
    $cnUnits = array('', '拾', '佰', '仟', '万', '拾', '佰', '仟', '亿');  
    $numStr = strval($num);  
    $numStr = array_reverse(str_split($numStr));  
    $result = '';  
    $zeroCount = 0;  
      
    for ($i = 0; $i < count($numStr); $i++) {  
        $digit = intval($numStr[$i]);  
        $unit = $cnUnits[$i % 4];  
          
        if ($digit === 0) {  
            $zeroCount++;  
        } else {  
            if ($zeroCount > 0) {  
                $result = $cnNums[0] . $result;  
            }  
            $zeroCount = 0;  
            $result = $cnNums[$digit] . $unit . $result;  
        }  
          
        if (($i + 1) % 4 === 0 && $digit !== 0) {  
            $result = $cnUnits[4 + intval(($i + 1) / 4) - 1] . $result;  
        }  
    }  
      
    $result = trim($result, $cnNums[0]); // 去除结果字符串两边的零  
    if (empty($result)) {  
        $result = $cnNums[0]; // 如果结果为空,则返回零  
    }  
      
    return '人民币' . $result . '元整';  
}  
  
// 示例用法  
echo numberToChinese(123456789); // 输出:人民币壹亿贰仟叁佰肆拾伍万陆仟柒佰捌拾玖元整

人民币中文汉字转数字

php 复制代码
function chineseToNumber($chinese) {  
    // 去除人民币和元整等字样  
    $chinese = preg_replace('/人民币|元整|元正|元|整|正/i', '', $chinese);  
    $cnNums = array('零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖');  
    $cnUnits = array('', '拾', '佰', '仟');  
    $unitPosition = array(1, 10, 100, 1000); // 个、十、百、千  
    $num = 0;  
    $position = 0; // 万位、亿位等的位置,初始为个位  
    $isPrevZero = false; // 前一个数字是否为零  
  
    $chinese = str_split($chinese);  
    for ($i = 0; $i < count($chinese); $i++) {  
        $char = $chinese[$i];  
        if (in_array($char, $cnNums)) {  
            $digit = array_search($char, $cnNums);  
            if ($digit === 0 && $isPrevZero) {  
                continue; // 连续的零只计算一个  
            }  
            $num += $digit * $unitPosition[$i % 4] * pow(10000, intval($position));  
            $isPrevZero = ($digit === 0);  
        } elseif (in_array($char, $cnUnits)) {  
            if ($char === '万' || $char === '亿') {  
                $position++;  
            }  
        }  
    }  
  
    return $num;  
}  
  
// 示例用法  
echo chineseToNumber('人民币壹亿贰仟叁佰肆拾伍万陆仟柒佰捌拾玖元整'); // 输出:123456789
相关推荐
BingoGo19 小时前
PHP 如何利用 Opcache 来实现保护源码
后端·php
BingoGo2 天前
2025 年 PHP 常见面试题整理以及对应答案和代码示例
后端·php
Bruce1233 天前
web专题之php代审(二)
php
BingoGo3 天前
PHP-FPM 深度调优指南 告别 502 错误,让你的 PHP 应用飞起来
后端·php
亿坊电商3 天前
物联网领域中PHP框架的最佳选择有哪些?
物联网·struts·php
wuzuyu3653 天前
用php做一个简易的路由
php·路由
老六ip加速器4 天前
手机ip隔离方法
tcp/ip·智能手机·php
rockmelodies4 天前
【PHP7内核剖析】-1.3 FPM
php
真正的醒悟4 天前
上网管理行为-ISP路由部署
服务器·php·接口隔离原则
张晓~183399481214 天前
短视频矩阵源码-视频剪辑+AI智能体开发接入技术分享
c语言·c++·人工智能·矩阵·c#·php·音视频