How can the str_replace function be used to simplify the process of replacing smiley codes with HTML in PHP?

When dealing with smiley codes in PHP, it can be tedious to manually replace each code with the corresponding HTML representation. The str_replace function can be used to simplify this process by replacing all instances of a smiley code with its corresponding HTML representation in one go. By using an array to map smiley codes to their HTML counterparts, we can easily perform the replacements efficiently.

// Define an array mapping smiley codes to their HTML representations
$smileyCodes = array(
    ':)' => '<img src="smiley.png" alt=":)" />',
    ':D' => '<img src="big_smiley.png" alt=":D" />',
    ':(' => '<img src="sad_smiley.png" alt=":(" />'
);

// Input string containing smiley codes
$inputString = 'Hello there! :) I am feeling happy :D';

// Replace all smiley codes with their HTML representations
$outputString = str_replace(array_keys($smileyCodes), array_values($smileyCodes), $inputString);

// Output the result
echo $outputString;