SiteKickr Web Development

SEO Friendly URLs with Regular Expressions

If you're creating dynamic pages from a database, you've probably heard the buzz about SEO friendly URLs. There's a little more work involved than simply passing an id to your database query, as in traditional query string URLs.

There are generally 3 things to consider:

  1. You'll need to reference your database stored content by a character string, instead of a numeric id.
  2. Adjustments will need to be made in your web server configuration, to allow it to serve pages that don't actually "exist".
  3. An algorithm to create SEO friendly URLs based on your content, generally the title of the page.

This post will deal with the third item in the list above. Using ColdFusion as an example, the following function leverages regular expressions to quickly create an SEO friendly URL from any string:

<cffunction name="stringToUrl" access="public" output="false">
    <cfargument name="input" required="true">
    <cfset normal = LCase(REReplaceNoCase(arguments.input, "[\s]|-", "_", "ALL"))>
    <cfset normal = REReplaceNoCase(normal, "[\W]|[\d]", "", "ALL")>
    <cfset normal = REReplaceNoCase(normal, "[_]+", "_", "ALL")>
    <cfset normal = Replace(normal, "_", "-", "ALL")>
    <cfreturn normal>
</cffunction>