In this code snippet you will learn how to create tag links in PHP. Many websites or let’s say Web 2.0 sites use a lot of so called “tags” to create a relevant search based on keywords. I find the most efficient way to do this is to store the tags as a simple comma delimited string in a Varchar field of a database table per record / row. In this example I assume you already know how to query a database to return a simple result set. This example simply provides the string manipulation in PHP…
< ?php $my_str = 'linux, apache, mysql, php'; $tags_arr = explode(',', $my_str); $new_arr = array(); foreach ($tags_arr as $tag) { $clean_tag = trim($tag); $new_arr[] = '<a href="/index.php?tag='.$clean_tag.'">'.ucword($clean_tag).''; } $tags_str = implode(', ', $new_arr); echo $tags_str; ?>
The above should output your comma delimited string into clickable tag links. If you want to get more creative, you can create a styled out tag cloud that alters the font size based on keyword density. Hopefully I can find some extra time to create a tutorial extending this one.
Enjoy!







This is a very informative post! Very simple and only a few lines of code. You should have seen what I was trying to come up with!