Skip to content

Instantly share code, notes, and snippets.

@TanmayChakrabarty
Last active November 22, 2023 09:55
Show Gist options
  • Save TanmayChakrabarty/bb5d8799cb72f7afe1a5f486481bdc74 to your computer and use it in GitHub Desktop.
Save TanmayChakrabarty/bb5d8799cb72f7afe1a5f486481bdc74 to your computer and use it in GitHub Desktop.
Creating User and SEO friendly URL slug in PHP and JavaScript
<?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