how to change value of an array based on value php

38 views Asked by At

i try to change roman numerals in a string to numeric value.

In order to find and replace the roman numerals in the array i tried str_replace() but the Output confirms that the method is not working.

$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
)

i have a dirty solution but im not quite happy with it

$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);

Maybe someone got a better solution than me

0

There are 0 answers