Friday, 10 August 2018

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.
  1. function fixForUri($string){
  2. $slug = trim($string); // trim the string
  3. $slug= preg_replace('/[^a-zA-Z0-9 -]/','',$slug ); // only take alphanumerical characters, but keep the spaces and dashes too...
  4. $slug= str_replace(' ','-', $slug); // replace spaces by dashes
  5. $slug= strtolower($slug); // make it lowercase
  6. return $slug;
  7. }
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.
  1. $string = '"I\'ve got a lovely *bunch* of coconuts!"';
  2. 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.

0 comments:

Post a Comment