How can PHP functions be used to replace text with images, such as smileys, in a script?
To replace text with images, such as smileys, in a script using PHP functions, you can create a mapping of text to image filenames. Then, use a function like str_replace() to replace the text with the corresponding image tag in your script. Finally, output the modified text with the images displayed.
<?php
// Mapping of text to image filenames
$smileys = array(
':)' => 'smiley.png',
':D' => 'laugh.png',
':(' => 'sad.png'
);
// Function to replace text with images
function replaceSmileys($text, $smileys) {
foreach ($smileys as $key => $image) {
$text = str_replace($key, '<img src="' . $image . '" alt="' . $key . '">', $text);
}
return $text;
}
// Example text with smileys
$text = 'Hello, how are you? :) I hope you are feeling great!';
// Output the modified text with images
echo replaceSmileys($text, $smileys);
?>