Skip to content

Instantly share code, notes, and snippets.

@GarySwift
Created March 28, 2017 18:32
Show Gist options
  • Save GarySwift/b4a8868203c9c54df9788fe3f3d930ba to your computer and use it in GitHub Desktop.
Save GarySwift/b4a8868203c9c54df9788fe3f3d930ba to your computer and use it in GitHub Desktop.
Change string into lowercase slug
<?php
/**
* Change string into lowercase slug
*
* @param $string Any string
* @return $string Converted string into slug
*/
function slug($string) {
# Lower case everything
$string = strtolower($string);
# Make alphanumeric (removes all other characters)
$string = preg_replace("/[^a-z0-9_\s-]/", "", $string);
# Clean up multiple dashes or whitespaces
$string = preg_replace("/[\s-]+/", " ", $string);
# Convert whitespaces and underscore to dash
$string = preg_replace("/[\s_]/", "-", $string);
return $string;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment