PHP function to generate a slug for SEO URLs

Increase SEO by using your article name/product name/category name/whatever in your URLs instead of a non-descriptive database ID.

function slug($string) {
    $string = trim($string);
    $string = strtolower($string);
    $string = str_replace('&', 'and', $string);
    $string = preg_replace('/[^a-z0-9-]/', '-', $string);
    $string = preg_replace('/-+/', "-", $string);
    return $string;
}
This entry was posted in Code Stuff. Bookmark the permalink.

2 Responses to PHP function to generate a slug for SEO URLs

  1. Jonathan Dusza says:

    this is great but is there perhaps a set of file, such as a mysql dump and some php files to test all this?

  2. Jess Barnes says:

    Hi Jonathan,

    I’m not sure what you’re getting at here. The idea of the post was just to provide a small piece of code to covert a string like “Hello World, how are you today?” into “hello-world-how-are-you-today” for use in creating SEO friendly URLs by stripping out all non-alphanumeric characters and converting spaces into hyphens.

    A real life example of this is in WordPress when you are creating a post, it will take the title of the post that you enter and use that to create the permalink URL that the post can be accessed by. This method is also useful for things like shopping carts where you can have the product name as part of the URL while keeping it tidy and valid.

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>