Generating an SEO friendly URL in PHP

Everyone wants pretty URLs right? Lots of key/pair GET values in URL strings look ugly and are bad for SEO. I was just messing about with a big database table of records that needed converting to SEO friendly urls and needed a quick and easy fuction to automate the process. When I need to do a certain job like this I tend to add a static function to a tools class that I keep in my library. I know this isn’t considered particularly good practice and I should refactor the code out into a url class but for small scripting jobs I’ve always found this way is a lot more efficient.

First thing we do is take the page name and replace all the spaces with hyphens, then strip out any non-alpha-numeric characters using regex. This will give you a nice URL that will make theĀ  SEO people at your company happy. I’ve also added a suffix option here that can be used to take care of any duplicates. The logic to handle this should be kept outside this function as it’s dependent on whatever database table you happen to be using at the time.

    /**
     * generates an SEO friendly url
     *
     * @param string $name
     * @param interger $suffix
     * @return string
     */
    public static function generateUrl($name, $suffix = 0)
    {

        $alias = str_replace(' ', '-', strtolower(trim($name)));
        $alias = preg_replace('/[^A-Za-z0-9-]/', '', $alias);
        $alias .= ($suffix > 0) ? $suffix : '';

        return $alias;

    }

By using this function in any admin scripts we can now generate urls for each record by looping through the database.

Eg. If the page title you have is “This is a new article! Is it helpful?”, it will be converted to “this-is-a-new-article-is-it-helpful”. Perfect for SEO.

This entry was posted in Open Source, PHP, SEO. Bookmark the permalink.

One Response to Generating an SEO friendly URL in PHP

  1. Pingback: Generating an SEO friendly URL in PHP | SEO Article Expert

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>