Snippet: Make a URL Friendly String

Posted on Tuesday 18th October 2011 by Andy Mills

Share this:
  • Share this on Facebook
  • Share this on Twitter
  • Share this on Digg
  • Share this on Del.icio.us
  • Share this on MySpace
  • Share this on tumblr

With SEO being such a huge part of the web development work I do thesedays, finding a way to create search engine-friendly URLs has become more important than ever.  When I first started creating dynamic websites in PHP / MySQL, they were filled with pages that had URLs like this:

view_news.php?news_id=1

Nowadays, I combine the Apache mod_rewrite module and a bit of PHP code to turn those awful URL strings into something a bit more palatable.  By adding a field in any tables which contain page data called 'url_tag', I an create a URL friendly string:

function make_url_tag($String)
{
    // First, replace all of the Punctuation with a Regular Expression Replace
    $Hyph_String = preg_replace('/([^a-zA-Z0-9]+)/', '-', $String);

    // Now, strip any excess Hyphens from the String
    $Trim_String = trim($Hyph_String, '-');

    // Finally, as an optional extra, make it Lowercase
    $Lower_String = strtolower($Trim_String);

    return $Lower_String;
}

Using this function, I can pass in, for example, the title of a news post, and get a URL friendly string in return.  I can then use a mod_rewrite line in the .htaccess file like:

RewriteRule ^News/([a-zA-Z0-9-_]+)\.html$ news.php?url_tag=$1

Now all the news.php file has to do is search for an entry in the news table with the url_tag specified in the URL variable:

 $News_Query = "SELECT * FROM news WHERE url_tag = '" .$_GET['url_tag'] ."'";

Now we can access the news page with a URL like:

News/url-friendly-tag.html