Skip to content

Instantly share code, notes, and snippets.

@richarddewit
Last active March 15, 2019 08:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save richarddewit/06692629a1503f931ff9d54002ffc14e to your computer and use it in GitHub Desktop.
Save richarddewit/06692629a1503f931ff9d54002ffc14e to your computer and use it in GitHub Desktop.
Slugify a string
<?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