How to convert a Roman numeral to integer in PHP?

kapa picture kapa · Jun 7, 2011 · Viewed 25.6k times · Source

Using PHP, I'd like to convert a string containing a Roman number into its integer representation. I need this because I need to make calculations on them.

Wikipedia on Roman numerals

It would suffice to only recognize the basic Roman numeral characters, like:

$roman_values=array(
    'I' => 1,
    'V' => 5,
    'X' => 10,
    'L' => 50,
    'C' => 100,
    'D' => 500,
    'M' => 1000,
);

That means the highest possible number is 3999 (MMMCMXCIX). I will use N to represent zero, other than that only positive integers are supported.

I cannot use the PEAR library for Roman numbers.

I found this great question on SO on how to test whether the string contains a valid Roman numeral:

How do you match only valid roman numerals with a regular expression?

What would be the best way of coding this?

Answer

andyb picture andyb · Jun 7, 2011

How about this:

$romans = array(
    '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,
);

$roman = 'MMMCMXCIX';
$result = 0;

foreach ($romans as $key => $value) {
    while (strpos($roman, $key) === 0) {
        $result += $value;
        $roman = substr($roman, strlen($key));
    }
}
echo $result;

which should output 3999 for the supplied $roman. It seems to work for my limited testing:

MCMXC = 1990
MM = 2000
MMXI = 2011
MCMLXXV = 1975

You might want to do some validation first as well :-)