10k views

Function to slugify strings in PHP

This is a function to slugify (replace non-ASCII characters with ASCII characters) strings in PHP. It tries to replace some characters like ñ or ç to a similar ASCII character (for example, it will transform a ñ to a n).

PHP
  1. /**
  2.  * Modifies a string to remove all 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. }
  31.  

­

Hey, I know that many of you are symfony users. If you are, and you use Doctrine, you don't need to use this function; you can just call the urlize function provided by the class Doctrine_Inflector.

Tags: PHP slugify strings

Embed: