Last active
March 15, 2019 08:49
-
-
Save richarddewit/06692629a1503f931ff9d54002ffc14e to your computer and use it in GitHub Desktop.
Slugify a string
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 | |
/** | |
* Converts text from | |
* "thing + (Beep) $%^boop" | |
* to | |
* "thing-beep-boop" | |
* | |
* @author Richard de Wit | |
* @link https://gist.github.com/richarddewit/06692629a1503f931ff9d54002ffc14e | |
* | |
* @param string $text input text | |
* | |
* @return string slugified text | |
*/ | |
function slugify($text) { | |
// Replace non letter or digits by - | |
$text = preg_replace('/[^\pL\d]+/u', '-', $text); | |
// Transliterate letters with diacritics, umlauts, etc. to plain letters | |
$text = iconv('utf-8', 'us-ascii//TRANSLIT', $text); | |
// Remove unwanted characters | |
$text = preg_replace('/[^-\w]+/', '', $text); | |
// Remove duplicate hyphens | |
$text = preg_replace('/-+/', '-', $text); | |
// Trim leading and trailing hyphens | |
$text = trim($text, '-'); | |
// Lowercase | |
$text = strtolower($text); | |
if (empty($text)) { | |
return ''; | |
} | |
return $text; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment