Created
December 1, 2021 14:44
-
-
Save ccfelix/f37e17572ae85742091e87be62dba2cb to your computer and use it in GitHub Desktop.
PHP: function slug
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 | |
/** | |
* 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