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…

1 year ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

1 year ago

FTP getting array of file details such as size using PHP

Using FTP and PHP to get an array of file details such as size and…

2 years ago

Creating Laravel form requests

Creating and using Laravel form requests to create cleaner code, separation and reusability for your…

2 years ago

Improving the default Laravel login and register views

Improving the default Laravel login and register views in such a simple manner but making…

2 years ago

Laravel validation for checking if value exists in the database

Laravel validation for checking if a field value exists in the database. The validation rule…

2 years ago