Created
May 17, 2012 03:55
-
-
Save craiga/2716157 to your computer and use it in GitHub Desktop.
slugify
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 <[email protected]> | |
* @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