Posted By

suibhne on 11/08/09


Tagged

php slug slugify


Versions (?)

Who likes this?

4 people have marked this snippet as a favorite

aleksanderek
xmartyxcorex
MeatRepeat
guillermoj88gmailcom


Slugify a String in PHP


 / Published in: PHP
 

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

  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
Posted By: ignace on November 21, 2009

For those not knowing to what 'slug' refers read this: http://codex.wordpress.org/Glossary#Slug

You need to login to post a comment.