Slugify a String in PHP


/ Published in: PHP
Save to your folder(s)

Function which will slugify a string for use in URLs, taking out any spaces and other non-URL useful characters.


Copy this code and paste it in your HTML
  1. /**
  2.  * Modifies a string to remove al non ASCII characters and spaces.
  3.  */
  4. static public function slugify($text)
  5. {
  6. // replace non letter or digits by -
  7. $text = preg_replace('~[^\\pL\d]+~u', '-', $text);
  8.  
  9. // trim
  10. $text = trim($text, '-');
  11.  
  12. // transliterate
  13. if (function_exists('iconv'))
  14. {
  15. $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
  16. }
  17.  
  18. // lowercase
  19. $text = strtolower($text);
  20.  
  21. // remove unwanted characters
  22. $text = preg_replace('~[^-\w]+~', '', $text);
  23.  
  24. if (empty($text))
  25. {
  26. return 'n-a';
  27. }
  28.  
  29. return $text;
  30. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.