Mar
14

Search a string for skype emoticons code

14 Mar 2009 by tonie in PHP

Yesterday I was reading my school's bulletin board, when I started thinking on what makes them smileys show up, when you type a particular code on a comment or post. So, after a few minutes I came up with a very basic PHP function, which searches strings for occurances of a pattern and replaces them with images.

For this example we are going to use the Skype Emoticons, which can be downloaded for free from here.

<?php
function text2smiley($text, $path, $animated=true) {
    $array = array(
        ':)' => '00-smile',
        ':(' => '01-sadsmile',
        ':D' => '02-bigsmile',
        ';)' => '05-wink',
        ':P' => '10-tongueout',
        '(smoke)' => '76-smoke',
        '(tmi)' => '84-tmi'
        
        // ... more items, cut for convenience purposes

    );
    foreach($array as $code => $smiley){
        if ($animated) {
            $text=str_replace($code, '<img alt="'.$code.'" src="'.$path.'/animated/emoticon-01'.$smiley.'.gif" />', $text);
        } else {
            $text=str_replace($code, '<img alt="'.$code.'" src="'.$path.'/static/emoticon-01'.$smiley.'.png" />', $text);
        }
    }
    return $text;
}
?>

So, how does the script work? We've created a function, called text2smiley with 3 parameters: $text, $path and $animated. First thing we do is fill in an array with keys and representing values. Keys are the actual code we are searching for to replace and the value is the name of the image we are replacing with. At the end of the function, we walk through each entry in the array, replacing the content of $key with the content of $value in $text. The $path parameter is the full (or relative to the file) path, where our Skype Emoticons are located, for ex. $path='http://localhost/skype_smileys';. $animated parameter is self-explanatory - can acquire true or false values. We could have used preg_replace() or ereg_replace() to achieve the same result, but according to PHP's manual:

If you don't need fancy replacing rules (like regular expressions), you should always use this function instead of ereg_replace() or preg_replace()

php, skype, emoticons, smileys

Speak your mind ( 0 Comments)

If you liked the article and want to contribute to it, please feel free to leave your comment. HTML tags are not allowed, but you can use the following BBCode to enhance your message: [url] [quote] [code] [b] [i] [u] [color].