Skip to content

Instantly share code, notes, and snippets.

@ccfelix
Created December 1, 2021 14:44
Show Gist options
  • Save ccfelix/f37e17572ae85742091e87be62dba2cb to your computer and use it in GitHub Desktop.
Save ccfelix/f37e17572ae85742091e87be62dba2cb to your computer and use it in GitHub Desktop.
PHP: function slug
<?php
/**
* Create a slug to use in a url
* Dependency: php_intl (extension)
*
* @author ClebioFelix
* @param string $text Text to transform
* @param bool $tolower Convert or not to lowercase
* @return string
*/
function slug($text, $tolower = true)
{
$allowed = '~[^-,;.a-z0-9\s]~iu';
$text = transliterator_transliterate('Any-Latin; Latin-ASCII', $text);
if ($tolower) {
$text = mb_strtolower($text);
}
$text = preg_replace($allowed, '', $text);
$text = preg_replace('~[.,;)(\s]+~', '-', trim($text));
$text = preg_replace('~-{2,}~', '-', $text);
return $text;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment