Skip to content

Instantly share code, notes, and snippets.

@craiga
Created May 17, 2012 03:55
Show Gist options
  • Save craiga/2716157 to your computer and use it in GitHub Desktop.
Save craiga/2716157 to your computer and use it in GitHub Desktop.
slugify
<?php
/**
* Slugify a string.
*
* Convert "Hello, world! It's Craig in 2012." to "hello-world-its-craig-in-2012".
* See test_slugify for more examples.
*
* @author Craig Anderson <craiga@craiga.id.au>
* @link https://gist.github.com/2716157
*/
function slugify($s)
{
$s = iconv(mb_detect_encoding($s), "ascii//TRANSLIT//IGNORE", $s); // transliterate to ASCII
$s = preg_replace("/['^]/", "", $s); // remove accents
$s = preg_replace("/[^a-zA-Z0-9]/", "-", $s); // replace non-word characters
$s = preg_replace("/\-+/", "-", $s); // remove double-hyphens
$s = trim($s, "-"); // remove start and end hyphens
$s = strtolower($s); // lowercase
return $s;
}
/**
* Assert that slugify works as expected.
*/
function test_slugify()
{
function assert_slugify_result($input, $expected)
{
$fail = false;
$actual = slugify($input);
if($actual != $expected)
{
printf("\nFAIL!\nslugify(\"%s\") != \"%s\"\nslugify(\"%s\") == \"%s\"\n", $input, $expected, $input, $actual);
$fail = true;
}
return $fail;
}
$numFails = 0;
$numFails += assert_slugify_result("Hello, World! It's Craig in 2012.", "hello-world-its-craig-in-2012");
$numFails += assert_slugify_result("Bonjour Café", "bonjour-cafe");
$numFails += assert_slugify_result("€200", "eur200");
$numFails += assert_slugify_result("Fußball", "fussball");
printf("\nTests completed. %d test%s failed.\n", $numFails, $numFails != 1 ? "s" : "");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment