What is the best way to replace specific characters in a string in PHP while maintaining case sensitivity?

When replacing specific characters in a string in PHP while maintaining case sensitivity, one approach is to use the str_replace function with an array of search and replace values. By specifying both uppercase and lowercase versions of the characters you want to replace, you can ensure that the case is preserved. Additionally, you can use the str_ireplace function for case-insensitive replacements.

// String with characters to be replaced
$string = "Hello World";

// Array of search and replace values for case-sensitive replacement
$replaceArray = array(
    'H' => 'X',
    'h' => 'x',
    'o' => 'Y',
    'r' => 'Z'
);

// Perform case-sensitive replacement
$newString = str_replace(array_keys($replaceArray), array_values($replaceArray), $string);

echo $newString; // Output: "XellY WZld"