0

我尝试将字符串中的罗马数字更改为数值。

为了查找和替换数组中的罗马数字,我尝试了 str_replace() 但输出确认该方法不起作用。

$string = "This is a Test String with Roman Numbers IV and V";
$string = strtolower($string);
$string = explode(" ", $string);
print_r($string);
$search = ['xv','xiv','xiii','xii','xi','x','ix','viii','vii','vi','v','iv','iii','ii'];
$replace = ['15','14', '13', '12', '11','10','9',  '8',  '7',  '6', '5','4', '3', '2'];
$newString = str_replace($search, $replace, $string);
print_r($newString);

String Output: 
Array
(
    [0] => this
    [1] => is
    [2] => a
    [3] => test
    [4] => string
    [5] => with
    [6] => roman
    [7] => numbers
    [8] => iv
    [9] => and
    [10] => v
)
newString Output:
Array
(
    [0] => this
    [1] => is
    [2] => a
    [3] => test
    [4] => string
    [5] => with
    [6] => roman
    [7] => numbers
    [8] => i5
    [9] => and
    [10] => 5
)

我有一个肮脏的解决方案,但我对它不太满意

$title = str_replace(' XV', ' 15', $title);
    $title = str_replace(' XIV', ' 14', $title);
    $title = str_replace(' XIII', ' 13', $title);
    $title = str_replace(' XII', ' 12', $title);
    $title = str_replace(' XI', ' 11', $title);
    $title = str_replace(' X ', ' 10', $title);
    $title = str_replace(' IX', ' 9', $title);
    $title = str_replace(' VIII', ' 8', $title);
    $title = str_replace(' VII', ' 7', $title);
    $title = str_replace(' VI', ' 6', $title);
    $title = str_replace(' V ', ' 5', $title);
    $title = str_replace(' IV', ' 4', $title);
    $title = str_replace(' III', ' 3', $title);
    $title = str_replace(' II', ' 2', $title);

也许有人比我有更好的解决方案

4

0 回答 0