Last active
April 30, 2020 10:12
-
-
Save zawyelwin/a324f967d2dc226c2257a145167110ad to your computer and use it in GitHub Desktop.
A php slug function from https://ourcodeworld.com/articles/read/253/creating-url-slugs-properly-in-php-including-transliteration-support-for-utf-8
This file contains hidden or 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 | |
function Slug($string){ | |
return strtolower(trim(preg_replace('~[^0-9a-z]+~i', '-', html_entity_decode(preg_replace('~&([a-z]{1,2})(?:acute|cedil|circ|grave|lig|orn|ring|slash|th|tilde|uml);~i', '$1', htmlentities($string, ENT_QUOTES, 'UTF-8')), ENT_QUOTES, 'UTF-8')), '-')); | |
} | |
$user = 'Cómo hablar en sílabas'; | |
echo Slug($user); // como-hablar-en-silabas | |
$user = 'Álix Ãxel'; | |
echo Slug($user); // alix-axel | |
$user = 'Álix----_Ãxel!?!?'; | |
echo Slug($user); // alix-axel |
This file contains hidden or 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 | |
public function slugify($text) | |
{ | |
// replace non letter or digits by - | |
$text = preg_replace('~[^\pL\d]+~u', '-', $text); | |
// transliterate | |
$text = iconv('utf-8', 'us-ascii//TRANSLIT', $text); | |
// remove unwanted characters | |
$text = preg_replace('~[^-\w]+~', '', $text); | |
// trim | |
$text = trim($text, '-'); | |
// remove duplicate - | |
$text = preg_replace('~-+~', '-', $text); | |
// lowercase | |
$text = strtolower($text); | |
if (empty($text)) { | |
return 'n-a'; | |
} | |
return $text; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment