You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP 7.4x-8x环境下罗马数字转阿拉伯数字实现方法

罗马数字转阿拉伯数字的PHP实现

既然你已经用NumberFormatter实现了阿拉伯数字转罗马数字,反向转换同样可以借助这个类完成,不需要额外造轮子。

实现代码

function romanNumeralToInt(string $roman): ?int {
    static $nf = new \NumberFormatter('@numbers=roman', \NumberFormatter::DECIMAL);
    // 解析罗马数字,返回整数或false(输入无效时)
    $value = $nf->parse($roman, \NumberFormatter::TYPE_INT32);
    
    return $value !== false ? (int)$value : null;
}

代码说明

  • 复用static修饰的NumberFormatter实例,避免重复初始化以提升性能
  • 使用parse方法并指定\NumberFormatter::TYPE_INT32类型,确保返回整数类型结果
  • 处理了无效输入场景:若解析失败(比如输入不是合法罗马数字),返回null,你也可以根据需求改成抛出异常或其他逻辑

使用示例

// 合法罗马数字转换
echo romanNumeralToInt('MCMXCIV'); // 输出 1994
// 无效输入返回null
var_dump(romanNumeralToInt('INVALID')); // 输出 NULL

内容的提问来源于stack exchange,提问作者Alexey Shatrov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 22:32:06