PHP Message Smiley Emotion

It is very convenient if we can show our feeling emotionally with our text message to someone we wish to understand our feeling. We might experienced with some social networkslike Facebook where smiley message is very convenient to express the feeling.

This function will display those smiley symbols by converting the smiley charactors to the smiley image. So, smiley image file is needed for working with this function. You may have your own smiley image design or your favorite one by just customizing the smiley images used in the function. The below script and instruction will show how the function works.

INSTRUCTION

The function works when the text is input, then the function finds the desired charactors to be replaced with the smiley image. When the disired charactors are found, the function checks what matchs them and replace them with a matched smiley image via a loop.

function display_smiley($message){
//image tag partern
$imgPath = '/images/emotions/';
$smileyImg = '<img width="14" src="'.$imgPath.'[imageFilename]" />';
//image filname array
$imgFilename=array(
'smiley-laughing.gif',
'smiley-smile.gif',
'smiley-wink.gif',
'smiley-tongue-out.gif',
'smiley-cool.gif',
'smiley-cry.gif',
'smiley-frown.gif',
'smiley-sealed.gif',
'smiley-undecided.gif',
'smiley-surprised.gif',
'smiley-kiss.gif',
'smiley-heart.png'
);
//charactors to be replaced
$findArray = array(
array(':D',':-D'),
array(':)',':-)'),
array(';)',';-)'),
array(':p',':-p'),
array('B)','B-)'),
array(':'(',':-'('),
array(':(',':-('),
array(':x',':-x',':X',':-X'),
array(':/',':-/'),
array(':o',':-o',':O',':-O'),
array(':*',':-*'),
array('<3')
);
//if array length not equal, return orginal string if(count($imgFilename)==count($findArray)){ //image tag array $imgFilenameTag=array(); foreach($imgFilename as $value){ $imgFilenameTag[]=str_replace('[imageFilename]',$value,$smileyImg); } //start replace text to image foreach($imgFilenameTag as $key=>$value){ $message = str_replace($findArray[$key],$value,$message); }
} return $message; }

With this funciton we have 6 variables to be used:

  • message : input string parameter
  • imgPath : image file path
  • smileyImg : image element
  • imgFilename : image filename array
  • findArray : disired charactors array to be replaced
  • imgFilenameTag : image element array with full attribute value

And 2 loops:

  • loop to create array imgFilenameTag to store the image element
  • loop to find and replace the disired charactors with the smile image files.

After the process done, the final converted string will be returned.

However, in the function we only assign some of the smile charactors so that you can add more smiley charactors and images by your own. And to add more, please remember that the variable imgFilename and findArray must be matched each other because the function will do nothing and return the orginal text if this two arrays' length is not equal.

Similar Tutorials

Comments