What are some best practices for dynamically replacing smiley codes with images in PHP?

When dynamically replacing smiley codes with images in PHP, it is important to use an associative array to map the smiley codes to their respective image URLs. This allows for easy lookup and replacement of the codes with the corresponding images. Additionally, using a regular expression with the 'preg_replace' function can efficiently replace the smiley codes with the image tags in the given text.

<?php
// Define an associative array mapping smiley codes to image URLs
$smileyMap = array(
    ':)' => 'smiley1.jpg',
    ':D' => 'smiley2.jpg',
    ':(' => 'smiley3.jpg'
);

// Sample text with smiley codes
$text = 'Hello! :) This is a test :D';

// Replace smiley codes with images
$textWithImages = preg_replace_callback('/(:\)|:D|:\()/i', function($match) use ($smileyMap) {
    return '<img src="' . $smileyMap[$match[0]] . '" alt="' . $match[0] . '">';
}, $text);

echo $textWithImages;
?>