Last active
November 22, 2023 09:55
-
-
Save TanmayChakrabarty/bb5d8799cb72f7afe1a5f486481bdc74 to your computer and use it in GitHub Desktop.
Creating User and SEO friendly URL slug in PHP and JavaScript
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($data, $max_length = 100){ | |
// Convert the string to lowercase | |
$string = mb_strtolower($data, 'UTF-8'); | |
// Create a transliterator for UTF-8 to ASCII | |
$transliterator = Transliterator::create('NFD; [:Nonspacing Mark:] Remove; NFC; Any-Latin; Latin-ASCII;'); | |
// Transliterate the string | |
$string = $transliterator->transliterate($string); | |
// Replace spaces with dashes, remove special characters | |
$string = preg_replace('/[^\p{L}\p{N}\s-]/u', '', $string); | |
$string = trim(preg_replace('/\s+/', '-', $string)); | |
// Remove unwanted characters | |
$string = preg_replace('/[^a-z0-9-]/', '', $string); | |
// Remove duplicate dashes | |
$string = preg_replace('/-+/', '-', $string); | |
// trim to max_length | |
$string = mb_substr($string, 0, $max_length, 'UTF-8'); | |
// Return the URL slug | |
return $string; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment