In addition to the above and your comment -
Your problem is that 'str_replace' performs replacements in the order they appear in your array as mentioned above. You can use the 'strtr' function (
PHP strtr Function[
^]) along with a custom replacement function to return the correct replacement, tested with all array items in
W3Schools Editor[
^] -
<!DOCTYPE html>
<html>
<body>
<?php
$reps = [
'I' => 1,
'II' => 2,
'III' => 3,
'IV' => 4,
'V' => 5,
'VI' => 6,
'VII' => 7,
'VIII' => 8,
'IX' => 9,
'X' => 10
];
$str = "word word IX word ...";
function replaceNumerals($matches) {
global $reps;
return $reps[$matches[0]];
}
$str2 = preg_replace_callback('/\b(?:' . implode('|', array_map('preg_quote', array_keys($reps))) . ')\b/', 'replaceNumerals', $str);
print_r($str2);
?>
</body>
</html>
Returns 'word word 9 word ...'