Connecting Tech Pros Worldwide Help | Site Map

Display Emoticons in Your Guestbook

Newbie
 
Join Date: Jun 2008
Posts: 25
#1   Jun 21 '08
Emoticons are very popular in the Internet these days. It seems like now every forums, mailing lists and guestbook support emoticons in their pages. If you write such applications, why not add them too? The basic concept is simple, all you need to do is replace smiley tags with the appropriate icons. For example, replace all :) with <img src="img/smile.gif" border="0" alt=":)" />

Here's a simple example to convert smileys to emoticons. You can get the icons from Yahoo Messenger and rename the icons like smile.gif, sad.gif, angry.gif, etc.

Expand|Select|Wrap|Line Numbers
  1. <?php
  2. function smiley2emoticons($text)
  3. {
  4.     $tags = array
  5.     (
  6.         ';)'  => '__winking.gif__;)__',
  7.         ':D'  => '__biggrin.gif__:D__',
  8.         ':-/' => '__confused.gif__:-/__',
  9.         '8->' => '__daydreaming.gif__8-&gt;__',
  10.         ':P'  => '__tongue.gif__:P__',
  11.         ':-*' => '__kiss.gif__:-*__',
  12.         ':-O' => '__surprise.gif__:-O__',
  13.         'X('  => '__angry.gif__X(__',
  14.         'B-)' => '__cool.gif__B-)__',
  15.         '>:)' => '__devil.gif__&gt;:)__',
  16.         ':((' => '__crying.gif__:((__',
  17.         ':))' => '__laughing.gif__:))__',
  18.         ':|'  => '__straightface.gif__:|__',
  19.         '=))' => '__rollingonthefloor.gif__=))__',
  20.         ':-c' => '__callme.gif__:-c__',
  21.         ':)]' => '__onthephone.gif__:)]__',
  22.         ':-?' => '__thinking.gif__:-?__',
  23.         '#o'  => '__doh.gif__#o__',
  24.         ':-w' => '__waiting.gif__:-w__',
  25.         ':)'  => '__smile.gif__:)__',
  26.         ':-)' => '__smile.gif__:)__',
  27.         ':('  => '__sad.gif__:(__',
  28.         ':-(' => '__sad.gif__:(__',
  29.         '(:|' => '__yawn.gif__(:|__'
  30.  
  31.     );
  32.     $new = strtr($text, $tags);
  33.     $new = preg_replace("/__([^_]*)__([^_]*)__/", "<img src=\"img/$1\" border=\"0\" alt=\"$2\" />", $new);
  34.     return($new);
  35. }
  36. ?>
  37.  
The function above will convert smiley tags to emoticons for the given text. Wanna see some demo? See smiley2emoticons in action!



Markus's Avatar
Moderator
 
Join Date: Jun 2007
Location: York, England, with wolves.
Posts: 4,936
#2   Jun 24 '08

re: Display Emoticons in Your Guestbook


To get rid of the regex, you could do it like so:

Expand|Select|Wrap|Line Numbers
  1.   /* this is just an example */
  2.   $str = "happy sad";
  3.   $search = array("/happy/", "/sad/");
  4.   $replace = array(":)", ":(");
  5.   echo preg_replace($search, $replace, $str);
  6.  
Reply