Clinton Montague

Developer, learner of things, functional programming enthusiast, hacker, and all round inquisitor.

Automatically creating 'short names' / 'slugs' for URIs

November 16, 2008

Please note!! I have shamelessly stolen this article from my old and (even if I do say so myself) rather boring blog. So please ignore the terrible writing style! I’ll rewrite this article in the future, but until then, I present you with version 1.0

This tutorial follows on from my mod_rewrite semi-tutorial which allowed you to use friendly-looking URIs. Now I will show you how to get PHP to automatically generate a unique short name for articles which you put on your website. The following simple function does all the work for you, and it is probably simpler than you first imagined.

What it does is change all non-url friendly charactors into an underscore, then compares this name with a list of existing names. If there is a name clash, add an underscore before the name and start again.

Voila!