Many people wonder how on php message boards and guestbook you turn and :) into a smiley face icon. This is very easy and this tutorial will show you how in two minutes. Observe the following code:
<?
$gbvalues=" :) :( :p ;) ;smirk :blush :angry :o ";
$smilies=array(
':)' => "<img src='images/smile.gif' />",
':(' => "<img src='images/sad.gif' />",
':p' => "<img src='images/tongue.gif' />",
';)' => "<img src='images/wink.gif' />",
';smirk' => "<img src='images/smirk.gif' />",
':blush' =>"<img src='images/blush.gif' />",
':angry' =>"<img src='images/angry.gif' />",
':o'=> "<img src='images/shocked.gif' />"
);
$gbvalues=str_replace(array_keys($smilies), array_values($smilies),
$gbvalues);
print "$gbvalues";
?>
First I created a string variable called gbvalues(php doesn't define variables so you can put in them whatever type you want) and assigned it a string value. Next, I declared a smilies array. The values on the left side of the => symbol are what the intial characters of the input are. The values on the right but is what they'll be converted into so on the right side I have put html image command to make it display certain images when those combinations of characters on the left side of the => are inputted. Next I call a string replace function. The line
$gbvalues=str_replace(array_keys($smilies), array_values($smilies), $gbvalues);
simply replaces the keyboard input on the left side of the => with the values on the right side you have defined. array_keys($smilies) and array_values($smilies) defines the name of the array you have declared to use in converting the symbols to icons. array_keys is the intial keyboard character input and array_values is what they will be converted to. The last parameter passed into the string str_replace function is the name of the variables you want to convert, in this case, gbvalues.
For Example using the above code(of course editing the image URLs after the img src html command to the URLs of my images) I get this output.
:) :( :p ;) ;smirk :blush :angry :o
becomes
after we use the string replace array function
Thats all there is to converting keyboard character input into images!
|