Creating A URI Slug With PHP

28th March 2008 - 2 minutes read time

The use of mod_rewrite on a site can have a powerful effect on search engine positioning, but to do it properly you will need to create a "slug" for each page. A slug is a lowercase alphanumeric version of the page title, with any spaces removed.

To get a slug you will need to use a function to turn a readable page title into a string that can be used as part of a URI.

This function is taken from Bramus and his excellent article about creating a post slug, and it does the job very nicely.

function fixForUri($string){
 $slug = trim($string); // trim the string
 $slug= preg_replace('/[^a-zA-Z0-9 -]/','',$slug ); // only take alphanumerical characters, but keep the spaces and dashes too...
 $slug= str_replace(' ','-', $slug); // replace spaces by dashes
 $slug= strtolower($slug);  // make it lowercase
 return $slug;
}

To use the function just pass your page title (and it can be as messy as you like) into the function and capture the output.

$string = '"I\'ve got a lovely *bunch* of coconuts!"';
echo fixForUri($string);

UPDATE:

I recently found a bug in this function where any trailing spaces where converted into hyphens and used as part of the slug. To stop this I have added a call to trim() in order to prevent this from happening.

Comments

Permalink

nice explaination

Anonymous (Sun, 05/17/2020 - 13:42)

Permalink

I want to slug domain/id=1 but I want domain/title or slug if I pass slug like (make small and good url, make-small-and-good-url) using mysql and php

Anonymous (Sat, 05/15/2021 - 17:16)

Add new comment

The content of this field is kept private and will not be shown publicly.