Create a URL slug from any string

Okay, so automically generating a friendly URL for a blog post or forum post from their titles doesn't really take a lot - but this snippet might make it easier for you:

function make_slug($orig, $length = 0)
{
  $slug = preg_replace('/[^a-zA-Z0-9]/', '-', $orig);
  $slug = preg_replace('/\-\-+/', '-', $slug);
  $slug = strtolower($slug);
 
  if ($length > 0) {
    // limits the length of the slug
    $slug = substr($slug, 0, $length);
  }
 
  if (strrpos($slug, '-') == strlen($slug) - 1) {
    // removes any ending -
    $slug = substr($slug, -1);
  }
 
  return $slug;
}

Basically, it will take a string like "This post is about URL slugs, and how to create them easily from a string" and then convert it to:

this-post-is-about-url-slugs-and-how-to-create-them-easily-from-a-string

Comments

Cool

I never thought about this way, javascript is all in my mind never thought i can do this way. respect!

Post new comment