Creating A URI Slug With PHP

28 March, 2008 | PHP Strings

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.

Write a comment