Posted By

shahways on 11/08/10


Tagged

url conversion characters


Versions (?)

String to slug


 / Published in: PHP
 

This filters a string into a "friendly" string for use in URL's. It converts the string to lower case and replaces any non-alphanumeric (and accented) characters with dashes. 2 alternatives available.

  1. function slug($str)
  2. {
  3. $str = strtolower(trim($str));
  4. $str = preg_replace('/[^a-z0-9-]/', '-', $str);
  5. $str = preg_replace('/-+/', "-", $str);
  6. return $str;
  7. }
  8.  
  9. function slugify($str, $replace="-")
  10. {
  11. // replace all non letters or digits by $replace
  12. $str = preg_replace('/\W+/', $replace, $str);
  13.  
  14. // trim and lowercase
  15. $str = strtolower(trim($str, $replace));
  16.  
  17. return $str;
  18. }

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: liamchapman on November 8, 2010

looks similar to mine: http://snipplr.com/view/43418/slugify-function-clean-urls/ :)

You need to login to post a comment.