Categories: Development

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

Nature
Animals
Summer

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

$split[1];//Animals
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.

Share

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

2 years ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

2 years ago

Early September spring shots

Some early September spring shots from a bushwalk, It is still too early for wildflowers.

3 years ago

Cloning an NVMe to SK Hynix Platinum P41 NVMe

I recently needed to clone over a smaller NVMe to a 2TB SK Hynix Platinum…

3 years ago

Using Laravel’s deleteDirectory to delete folders and their contents

If you ever needed a simple solution in Laravel to delete an entire directory and…

3 years ago

How to allow only 1 user to register in a Laravel application

How to enforce only one user to register or be registered in a Laravel web…

3 years ago