'Roman numerals to numbers in string
I have this string:
$string = 'Hello IV WorldX';
And I want to replace all roman numerals to integers.
I have the following function to convert roman to integer:
function roman2number($roman){
$conv = array(
array("letter" => 'I', "number" => 1),
array("letter" => 'V', "number" => 5),
array("letter" => 'X', "number" => 10),
array("letter" => 'L', "number" => 50),
array("letter" => 'C', "number" => 100),
array("letter" => 'D', "number" => 500),
array("letter" => 'M', "number" => 1000),
array("letter" => 0, "number" => 0)
);
$arabic = 0;
$state = 0;
$sidx = 0;
$len = strlen($roman);
while ($len >= 0) {
$i = 0;
$sidx = $len;
while ($conv[$i]['number'] > 0) {
if (strtoupper(@$roman[$sidx]) == $conv[$i]['letter']) {
if ($state > $conv[$i]['number']) {
$arabic -= $conv[$i]['number'];
} else {
$arabic += $conv[$i]['number'];
$state = $conv[$i]['number'];
}
}
$i++;
}
$len--;
}
return($arabic);
}
echo roman2number('IV');
Works great (try it on ideone). How do I search & replace through the string to replace all instances of roman numerals. Something like:
$string = romans_to_numbers_in_string($string);
Sounds like regex needs to come to the rescue... or?
Solution 1:[1]
Here's a simple regex to match roman numerals:
\b[0IVXLCDM]+\b
So, you can implement romans_to_numbers_in_string like this:
function romans_to_numbers_in_string($string) {
return preg_replace_callback('/\b[0IVXLCDM]+\b/', function($m) {
return roman2number($m[0]);
},$string);
}
There are some problems with this regex. Like, if you have a string like this:
I like roman numerals
It will become:
1 like roman numerals
Depending on your requirements, you can let it be, or you can modify the regex so that it doesn't convert single I's to numbers.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
