How to convert Roman numerals to Number in PHP
Snippet
Use the following function to convert any Roman numerals into integer numbers.
<?php
/**
* @param string $roman
* @return int
*/
function romanToNumber($roman){
$roman = strtoupper($roman);
$romans = [
'M' => 1000,
'CM' => 900,
'D' => 500,
'CD' => 400,
'C' => 100,
'XC' => 90,
'L' => 50,
'XL' => 40,
'X' => 10,
'IX' => 9,
'V' => 5,
'IV' => 4,
'I' => 1,
];
$result = 0;
foreach ($romans as $key => $value) {
while (strpos($roman, $key) === 0) {
$result += $value;
$roman = substr($roman, strlen($key));
}
}
return $result;
}
//uisng
echo romanToNumber('mm'); // 2000
echo romanToNumber('XIV'); // 14
If you need to convert this online, you can use our free tool - Roman numerals to Number Converter.