Search code examples
phpstringdrupalslug

drupal: standard way for creating a slug from a string


A slug on this context is a string that its safe to use as an identifier, on urls or css. For example, if you have this string:

I'd like to eat at McRunchies!

Its slug would be:

i-d-like-to-eat-at-mcrunchies

I want to know whether there's a standard way of building such strings on Drupal (or php functions available from drupal). More precisely, inside a Drupal theme.

Context: I'm modifying a drupal theme so the html of the nodes it generates include their taxonomy terms as css classes on their containing div. Trouble is, some of those terms' names aren't valid css class names. I need to "slugify" them.

I've read that some people simply do this:

str_replace(" ", "-", $term->name)

This isn't really a enough for me. It doesn't replace uppercase letters with downcase, but more importantly, doesn't replace non-ascii characters (like à or é) by their ascii equivalents. It also doesn't remove "separator strings" from begining and end.

Is there a function in drupal 6 (or the php libs) that provides a way to slugify a string, and can be used on a template.php file of a drupal theme?


Solution

  • You can use built in Drupal functions to do this.

    $string = drupal_clean_css_identifier($string);
    $slug = drupal_html_class($string);
    

    functions will do the trick for you.