How can the issue of multiple character replacements affecting each other be resolved when generating a key from a user input in PHP?

Issue: When generating a key from user input in PHP and replacing multiple characters, the replacements can affect each other if not handled correctly. To resolve this, we can use a temporary placeholder for each replacement to ensure they do not interfere with each other. PHP Code Snippet:

$userInput = "Hello World";
$replacements = [
    'H' => 'X',
    'o' => 'Y',
    'l' => 'Z'
];

$placeholder = '###'; // Temporary placeholder

// Replace each character with a temporary placeholder
foreach ($replacements as $search => $replace) {
    $userInput = str_replace($search, $placeholder, $userInput);
}

// Replace the temporary placeholder with the correct replacements
$userKey = str_replace($placeholder, array_values($replacements), $userInput);

echo $userKey; // Output: "XYZZo WYrZd"