2011
04.28

For a project I was working on I was in desperate need for a tool to generate slugs. Of course there are like million functions that can do that. We have the Mootools function String.Slugify, we have cakePHP’s function Inflector::slug et cetera. But there are no commandline or online tools that use these functions. So I created them! The commandline version is write in PHP and looks like this:

< ?php
setlocale(LC_ALL, 'en_US.UTF8');

if ($argc < 2)
{
  echo $argv&#91;0&#93;." <to slug text>\n";
  exit(1);
}

$words = $argv;
array_shift($words);

echo "\n";
echo toAscii(implode(' ', $words));
echo "\n\n";

function toAscii($str, $replace = array(), $delimiter = '-')
{
  if( !empty($replace) )
  {
    $str = str_replace((array)$replace, ' ', $str);
  }

  $clean = iconv('UTF-8', 'ASCII//TRANSLIT', $str);
  $clean = preg_replace("/[^a-zA-Z0-9\/_|+ -]/", '', $clean);
  $clean = strtolower(trim($clean, '-'));
  $clean = preg_replace("/[\/_|+ -]+/", $delimiter, $clean);

  return $clean;
}
?>

And this is how you use it:

php slugify.php A string to slugify

# ouput
a-string-to-slugify

non PHP version, but this way I could also use it online. And that’s what I did. Slugify, my online slug generator uses the same function.

References:

4 comments so far

Add Your Comment
  1. Blaze Castaneda

    Your Coding of Slug Generator will Surely help to the CakePHP Developer Who are looking for it?

  2. Lars Gyrup Brink Nielsen

    Hi,

    I actually use your tool on a weekly basis. Could you improve it by slugifying Danish letters like this:
    Ø -> oe
    ø -> oe
    Å -> aa
    å -> aa

    Thanks 🙂

  3. Makell

    Can you make a version that supports multiple lines? I have text strings (thousands of them) that need to be converted to slug case and I have to do it line by line.

  4. Why not run in in a loop?

    http://stackoverflow.com/a/1521498/138779