What are some best practices for implementing bbcode functions with smilie replace in PHP?

When implementing bbcode functions with smilie replace in PHP, it is important to first define an array mapping smilie codes to their corresponding image URLs. Then, use a regular expression to search for these smilie codes in the input text and replace them with the appropriate image tags. Finally, make sure to properly escape any special characters in the smilie codes to prevent injection attacks.

// Define an array mapping smilie codes to image URLs
$smilies = array(
    ':)' => 'smile.png',
    ':(' => 'sad.png',
    ':D' => 'laugh.png'
);

// Function to replace smilie codes with image tags
function replaceSmilies($text, $smilies) {
    foreach($smilies as $code => $img) {
        $text = preg_replace('/' . preg_quote($code, '/') . '/', '<img src="' . $img . '">', $text);
    }
    return $text;
}

// Example usage
$inputText = "Hello world! :) This is a test :D";
$outputText = replaceSmilies($inputText, $smilies);
echo $outputText;