Simple BBcode part 1

In this tutorial i will show you how to make a simple BBcode function for smilies.
What we want to do is to replace all the ":)" with "<img src='smile'>".

Lets say that this is the text we want to format:
Hello bob :) Sup in da h00d d00d? :D lolz

In this text we have 2 smilies: :) and :D when we are done with our script these will be replaced by <img> tags. So lets start with setting up a function:

<?php function smilies($text){ }?>

Not much to say about that so let's go on to the next step.

Were going to store all the smiley code and html code inside 1 array called $smilies.
The $smilies array will have 2 arrays inside it. 1 for smilie codes and 1 for the html codes:

<?php function smilies($text){ $smilies['plaintext'] = array(":)",":D",":("); $smilies['htmltext'] = array("<img src='happy.png'>","<img src='grin.png'>","<img src='sad.png'>"); } ?>

The $smilies structure will now look like this:

Array ( [plaintext] => Array ( [0] => :) [1] => :D [2] => :( ) [htmltext] => Array ( [0] => <img src='happy.png'> [1] => <img src='grin.png'> [2] => <img src='sad.png'> ) )

Note that :) is number 0 and is also 0 and so on... This is very important for this to work properly.

Now, lets move on to the next step:
What we have to do now, is to prase through the text and replace all the smiley codes with the html codes.

<?php function smilies($text){ $smilies['plaintext'] = array(":)",":D",":("); $smilies['htmltext'] = array("<img src='happy.png'>", "<img src='grin.png'>", "<img src='sad.png'>"); $text = str_replace($smilies['plaintext'],$smilies['htmltext'],$text); return $text; } ?>

We use str_replace() wich replaces all the $smilies['plaintext'] with $smilies['htmltext'] from $text.
"return $text;" simply returns the finished output.

And thats it!

If you want to test it you can try this:

<?php function smilies($text){ $smilies['plaintext'] = array(":)",":D",":("); $smilies['htmltext'] = array("<img src='happy.png'>","<img src='grin.png'>","<img src='sad.png'>"); $text = str_replace($smilies['plaintext'],$smilies['htmltext'],$text); return $text; } echo smilies("Hello bob :) Sup in da h00d d00d? :D lolz"); ?>

Wich will output:

Hello bob <img src='happy.png'> Sup in da h00d d00d? <img src='grin.png'> lolz

If you got any questions or comments, please post it in the forum or use the contact page to contact me :)



Want to get in touch? Got some feedback for me? or a couple of requests? Follow me at twitter:
@ThomasPedersen

Need a reliable webhost? Take my word for it and go with Hostgator Green Web Hosting by HostGator



Warning: fread(): Length parameter must be greater than 0 in /customers/f/2/7/n1studios.net/httpd.www/minicounter.php on line 17