0

Right now when users press a link in my php webapplications they are send to a page with url's like this: domain.com/faq/item/18483/ or domain.com/blog/item/37476. But I want to add a title to these url so the user will have a clue what's behind the link (example: I share a link to a friend) like this: domain.com/faq/item/18483/I-have-a-question.

If I have titles like this:

  • this is a faq item
  • blog ®!@# message &hello&

What is the best way to sanitize and convert them to this format:

  • this-is-a-faq-item
  • blog-message-hello

Actually just like stackoverflow does with my title I want to create urls like this: http://stackoverflow.com/questions/22042539/how-to-generate-url-slugs-seo-urls-from-raw-input/

botenvouwer
  • 4,334
  • 9
  • 46
  • 75
  • 1
    This question has some of the suggestions: http://stackoverflow.com/questions/1432463/how-do-i-sanitize-title-uris – hopsoo Feb 26 '14 at 13:17

1 Answers1

1

You could use a regular expression to change everything that isn't alphanumeric into a hyphen:

function slugify($string) {
    // Make the whole string lowercase
    $slug = strtolower($slug);
    // Replace utf-8 characters with 7-bit ASCII equivelants
    $slug = iconv("utf-8", "ascii//TRANSLIT", $input);
    // Replace any number of non-alphanumeric characters with hyphens
    $slug = preg_replace("/[^a-z0-9-]+/", "-", $string);
    // Remove any hyphens from the beginning & end of the string
    return trim($slug, "-");
}

The outputs for your sample strings are:

echo slugify("this is a faq item");         // this-is-a-faq-item
echo slugify("blog ®!@# message &hello&");  // blog-message-hello
Glitch Desire
  • 14,632
  • 7
  • 43
  • 55
  • Oh just tried this: http://stackoverflow.com/questions/1432463/how-do-i-sanitize-title-uris But still your answer is right. – botenvouwer Feb 26 '14 at 13:29
  • @sirwilliam Added a couple more steps to lowercase the slug & replace international characters (accented, umlaut, etc) with their 7-bit ASCII equivalents. – Glitch Desire Feb 26 '14 at 13:31