Advertisement
Neophitus

PHP: Slug Function

Nov 24th, 2021
249
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.63 KB | None | 0 0
  1. <?php
  2.  
  3. /**
  4.  * Create a slug to use in a url
  5.  * Dependency: php_intl (extension)
  6.  *
  7.  * @author Neophitus
  8.  * @param string $text Text to transform
  9.  * @param bool $tolower Convert or not to lowercase
  10.  * @return string
  11.  */
  12. function slug($text, $tolower = true)
  13. {
  14.     $allowed = '~[^-,;.a-z0-9\s]~iu';
  15.  
  16.     $text = transliterator_transliterate('Any-Latin; Latin-ASCII', $text);
  17.     if ($tolower) {
  18.         $text = mb_strtolower($text);
  19.     }    
  20.     $text = preg_replace($allowed, '', $text);
  21.     $text = preg_replace('~[.,;)(\s]+~', '-', trim($text));
  22.     $text = preg_replace('~-{2,}~', '-', $text);
  23.  
  24.     return $text;
  25. }
  26.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement