Creating A URI Slug With PHP

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);


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.


nice explaination


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


Add new comment

The content of this field is kept private and will not be shown publicly.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.
4 + 10 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.