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.

function generateShortName ($name)
	$name = preg_replace("#([^A-Za-z0-9_-])+#", '_', $name);
	$objects = //some code to find objects
		$conflict = false;
		foreach ($objects as $object)
			if (strcasecmp ($name, $object->shortName)==0)
				$conflict = true;
				$name = '_' . $name;
	} while ($conflict);
	return $name;

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.