Make an SEO friendly URL in PHP

Just like WordPress creates it’s slugs or friendly URLs, I had to write some code to achieve the same for a customer running a custom web application.

Here’s how I did it.

// KB changed the crappy built in function
function make_seo_url($in) {
$out = strtolower($in);
$out= trim($out);
$out = preg_replace("`\[.*\]`U","",$out);
$out = preg_replace('`&(amp;)?#?[a-z0-9]+;`i','-',$out);
$out = htmlentities($out, ENT_COMPAT, 'utf-8');
$out = preg_replace( "`&([a-z])(acute|uml|circ|grave|ring|cedil|slash|tilde|caron|lig|quot|rsquo);`i","\\1", $out);
$out = preg_replace( array("`[^a-z0-9]`i","`[-]+`") , "-", $out);
return $out;
}

So, taking a string like;

Rock Climbing Experience Plus One Year Membership for £15 at Rock Over Climbing (67% Off)

We will get;

rock-climbing-experience-plus-one-year-membership-for-15-at-rock-over-climbing-67-off

Making a really SEO rich URL string you can use in your code.

PS. It also removes back ticks – WordPress does not.

Author: Kieran Barnes

Kieran is a PHP developer with 15 years commercial experience. Specialist in WordPress, CakePHP, CubeCart and all things PHP.

Leave a Reply

Your email address will not be published. Required fields are marked *