Creating and parsing emoticons

Adding emoticons

Using JavaScript you can easily add emoticons to your messages. Firstly create some emoticons and think of a few characters to represent them.

<a href="addCode(':)');">Add smilie</a>

<textarea name="message" id="message"></textarea>

This example shows the text area that we are going to use and a sample link. We now need to make the the function addCode.

function addCode(type)
   document.getElementById('message').value += type;

This functions gets the text currently in the text box and appends the value sent as the parameter.

Processing the code

When the user submits the text we need to find these characters and replace them by there image equivalent.

   $message = $_POST['message'];
   $find = new array(':)', ':-)');
   $replace = new array('<image src="smile.png" alt="Smile emoticon" />',
                        '<image src="bigSmile.png" alt="Big smile emoticon" />');
   $message = str_replace($find, $replace, $message);

This code simply finds the appropriate characters and replaces them with an image equivalent. To add more icons simply change the array values.

Adding format tags

As well as emoticons you can also allow the user to add basic elements to the text area such as making the text bold. This can be done by prompting the user to enter the bold text and then inserting the text into the text area. By processing the information this way no HTML code is being inserted into the message or being stored.

function addBold()
   var message = window.prompt("Bold text input:", "Bold text.");
   if(message != null) document.getElementById('message').value += "[b]" + message + "[/b]";

Providing the user enters text into the dialog box this code surrounds the bold text with [b] [/b] and enters it into the text area.

Processing the code (in PHP)

Now that the user has entered the code we need to replace the code when we display it on a web page. To do this we will use a regular expression.

$message = preg_replace('/\[b\](.*?)\[\/b\]/','<strong>\\1</strong>',$message);

This code replaces all the text within the [b] [/b] and replaces it with the HTML equivalent.



No tags