title

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