PHP function to create SEO friendly URL, Unix friendly file names

This is a useful function for creating SEO friendly URL's.  It's also handy for creating Unix friendly file names.  

It simply removes anything that isn't a number or a letter and replaces it with a hypen (or any other character you pass... such as an underscore.) 

function seome($str, $char = '-')
{
  // convert non-alphanumeric to dashes
  $str = preg_replace("([^A-Za-z0-9])", $char, $str);

  // replace 2 or more dashes with single dashes
  $str = preg_replace("/(-){2,}/m", $char, $str);

  // remove any trailing or leading dashes
  $str = trim($str, $char);

  return $str;
}

November 6, 2011 at 4:47pm / Code, General Web Programming, PHP 

Comments On This Entry

That insight's just what I've been looikng for. Thanks!

Kamron @ 06:38:02 PM, Sunday, January 8, 2012

Compose New Blog Comment
    required = required field         warning HTML and URL's are not allowed

[back to main]