Convert String to Web-Friendly Slug

Pass any text string through this PHP function to create a web-friendly slug.

function create_slug($text) {

    // Lower case everything
    $text = strtolower($text);
    
    // Make alphanumeric (removes all other characters)
    $text = preg_replace("/[^a-z0-9_\s-]/", "", $text);
    
    // Clean up multiple dashes or whitespaces
    $text = preg_replace("/[\s-]+/", " ", $text);
    
    // Convert whitespaces and underscore to dash
    $text = preg_replace("/[\s_]/", "-", $text);

    return $text;
}

This note is tagged:

Adam Walter is a front-end developer, lover of WordPress, and Director of Development at Vital in Portsmouth, NH. Read more about me →