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:

2 comments so far

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

  2. 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 🙂