Last time I had talked about using .htaccess to make automatic seo-friendly URLs here: http://forum.codecal...access-php.html. In my tutorial requests (at my subdomain) somebody requested that I write about URL slugs, or rather generating an URL-friendly name out of a title a user may have entered.
This is a complementary tutorial to the linked post as that uses a custom mod_rewrite and this implements a friendly GET request (the two can be used together or apart), so I will link the two together for convenience.
Start:
To make an URL out of a small title the user submits can be hard, imagine the case where they submit a piece of code to a site. The site may throw back an automatic ID, and the submission result is this:
ID: 24141 Title: How to get INT_MAX Desc: This is how to get it when it is not known Fixed URL: snippet.php?id=24141This URL ID is bad because of two things.
- The user can not distinguish the page by number alone
- Search engines do not know what the ID number means
/**
* Return URL-Friendly string slug
* @param string $string
* @return string
*/
function seoUrl($string) {
//Unwanted: {UPPERCASE} ; / ? : @ & = + $ , . ! ~ * ' ( )
$string = strtolower($string);
//Strip any unwanted characters
$string = preg_replace("/[^a-z0-9_\s-]/", "", $string);
//Clean multiple dashes or whitespaces
$string = preg_replace("/[\s-]+/", " ", $string);
//Convert whitespaces and underscore to dash
$string = preg_replace("/[\s_]/", "-", $string);
return $string;
}Tests:These unfriendly titles:
?id=get int_max ?id=return INT_MAX ?id=This does a lot of things. ?id='#define test - $define (here), + @three_functions test! ?id=Already --d-ashes in here-here!Become these URL-friendly titles:
?id=get-int-max ?id=return-int-max ?id=this-does-a-lot-of-things ?id=define-test-define-here-three-functions-test ?id=already-dashes-in-here-hereYou can store these in a simple `idname` VARCHAR(50) column along with the numeric ID. You can retrieve your SQL results the same as using your numeric ID, except we use the `idname` column. Simply:
$res =
mysql_query("SELECT foobar FROM `tbl_posts` WHERE `idname` = '" . mysql_real_escape_string($_GET['id']) . "'";Hints:You will see things like vBSEO or Wordpress append a random number at the end. This can be the numeric ID or a random number. Personally the numeric ID is a good choice, as this means no two posts will have the same name accidentally, therefor 'introduction-to-foo2014' and 'introduction-to-foo2-12495' will be different and distinguishable. Feel free to experiment.


Sign In
Create Account

Back to top










