Managing tags within a string with PHP

By tags I mean hashtags or “describers” often only just a single word but sometimes more. Handling them in PHP is different to most other variables as they’re often singular and an unknown amount.

An obvious way could be creating columns in a DB for each tag such as tag1, tag2, tag3 or alternatively a better space saver and cleaner method is just one `tags` column and put all the tags into a string.

Take the example with a string of tags

$string = "Nature, Animals, Summer";

Each one is a tag, these could have been submitted in a form for an image upload and instead of separating them keeping them as a string is fine. Similar systems are used for YouTube where the uploader specifies the tag and separates them with a  ,

Through using explode the string can be split into an array of “strings”

$split = explode(',', $string);

Here we are splitting were the , (comma) is.

Outputting the whole $split variable will look like


More importantly you can access them individually as you would normally with a PHP array

echo "Picture tags are: #".trim($split[0])." #".trim($split[1])." #".trim($split[2])."";//Picture tags are: #Nature #Animals #Summer

Note using trim() gets rid of spaces before and after words in a string.