Convert string into slug with single-hyphen delimiters only

Atif Mohammed Ameenuddin picture Atif Mohammed Ameenuddin · Jun 11, 2010 · Viewed 28.8k times · Source

I would like to sanitize a string in to a URL so this is what I basically need:

  1. Everything must be removed except alphanumeric characters and spaces and dashed.
  2. Spaces should be converter into dashes.

Eg.

This, is the URL!

must return

this-is-the-url

Answer

SilentGhost picture SilentGhost · Jun 11, 2010
function slug($z){
    $z = strtolower($z);
    $z = preg_replace('/[^a-z0-9 -]+/', '', $z);
    $z = str_replace(' ', '-', $z);
    return trim($z, '-');
}