The AL2 Blog

April 7, 2010

Creating SEO-friendly URLs using PHP

If you’ve used WordPress or done much PHP developing you’ll probably be familiar with the concept of SEO-friendly URLs. That is, an informative link such as http://www.al2webdevelopment.com/blog/2010/04/07/creating-seo-friendly-urls-using-php/ which tell you nicely what the link is about, rather than something like blog.com?post=42.

There are plenty of functions out there that will create a friendly URL for you. This post shows you how to utilise one of these functions in a user friendly way.

This tutorial utilises the JQuery library, and uses its AJAX functionality, so you’ll want to make sure you are familiar with these before continuing.

Demo

Try a demo. This scenario assumes you are entering an news article title, but of course you can use it for anything you like. Try putting some punctuation in, and capital letters and you’ll see that these are nicely removed for you.

View demo

How it works

This feature uses a custom PHP function on a blog by asvin to create the URL. Let’s have a look at this function.

function friendlyURL($string){
    	$string = str_ireplace("'", "", $string);
			$string = preg_replace("`\[.*\]`U","",$string);
			$string = preg_replace('`&(amp;)?#?[a-z0-9]+;`i','-',$string);
			$string = htmlentities($string, ENT_COMPAT, 'utf-8');
			$string = preg_replace( "`&([a-z]) (acute|uml|circ|grave|ring|cedil|slash|tilde|caron|lig|quot|rsquo); `i" "\\1", $string );
			$string = preg_replace( array("`[^a-z0-9]`i","`[-]+`") , "-", $string);

			return strtolower(trim($string, '-'));
		}

This is all well and good, but how do we make it user friendly?

The Clever Bit

I decided to display the SEO-friendly URL on the fly, so the user can see it as it is being created. I also used it in a text field as we can assume it is being sent to a database, and it also gives the user the opportunity to edit the URL if required.

It does this by sending an AJAX request on the ‘keyup’ event on the top input box. As each character is entered, an AJAX request is sent, sending the article headline. The friendly URL is returned and entered into the URL text input field.

The Code

The HTML for the form..

The JQuery to make the magic happen…

$('#title').keyup(function(){
		//Create SEO friendly URL on the fly
		$.ajax({
			type: "GET",
			cache: false,
			url: "[php file location]?title=" + $(this).val(),
			success: function (msg){
			$('#seoTitle').val(msg);
			}
		});
	});

The PHP page that the AJAX calls…

	if($_GET['title']){
		$seoURL = friendlyURL($_GET['title']);
		echo $seoURL;
	}

There you go…

Utilising this code, you can now have an on-the-fly SEO-friendly URL generator!

Filed under: Development,Programming,SEO — Tags: , , , — Andy Long @ 8:18 pm

Powered by WordPress