Pretty URL Creating

published on January 2nd, 2008 · more from the blog →

Wordpress users of the mod_rewrite feature will notice that post titles are adjusted to make them look / work nicer.

As I plan to attack my gallery with this kind of feature (and my boss attempted it earlier) I thought i'd have a play myself. After a lil bit of Google bashing and seeing numerous other attempts at making something similar I got bored with their stupidity and wrote my own... I know it doesn't cover every random character out there but it gets the most common..

I know what your thinking... show me the money... well ok.. here it is...

function string_to_url_slug($string){
	$string = html_entity_decode(strtolower($string));
	//replace illegal chars with -'s
	$illegalchars = array(" ","." , "," ,"/", "'", "\\", "*", "@", "!", "\"", "=", "_", "-", "?", "", "", "", "$", "", "", "^", "%", "(", ")", ":", ";",  "|", "~", "`", "#", "{", "}", "+", "[", "]","","<",">");
	$string = str_replace($illegalchars,"-",$string);
	// replace & with -and-
	$string = str_replace('&','-and-',$string);
	// remove duplicate -'s
	while (strpos($string,'--')!==false){
		$string = str_replace('--','-',$string);
	}
	// remove trailing -'s and return
	return trim($string,'-');
}

For example passing it the string: hello there & let g&o %$!!!!!!!!'"!!!!!i!!!@ love^*() you ()*
Would return this: hello-there-and-let-g-and-o-i-love-you

Just like that :-)