How can arrays be effectively used to replace smileys with images in PHP?

To replace smileys with images in PHP, we can use an array where the keys are the smiley strings to be replaced and the values are the corresponding image filenames. We can then iterate over the array and use str_replace function to replace the smiley strings with the image tags in the content.

<?php

// Array mapping smiley strings to image filenames
$smileyArray = array(
    ':)' => 'smile.png',
    ':(' => 'sad.png',
    ':D' => 'laugh.png'
);

// Sample content with smileys
$content = "Hello there! :) How are you today? :D";

// Replace smileys with images
foreach ($smileyArray as $smiley => $image) {
    $content = str_replace($smiley, '<img src="' . $image . '">', $content);
}

echo $content;

?>