Skip to content

Instantly share code, notes, and snippets.

@borzilleri
Created June 28, 2011 23:31
Show Gist options
  • Save borzilleri/1052501 to your computer and use it in GitHub Desktop.
Save borzilleri/1052501 to your computer and use it in GitHub Desktop.
method for generating slugs
public static function slug($s, $maxLength = null) {
// Make the string lower case
$s = strtolower($s);
// Turn forward slashes into spaces.
// NOTE: We turn them into spaces, so they're properly condensed down to
// a single dash later on.
$s = str_replace('/',' ',$s);
// Remove any non-alphanumeric, space, or hyphen characters
$s = preg_replace("/[^a-z0-9\s-]/", "", $s);
// Replace consecutive space/hyphens with a single space (trimming edge spaces)
$s = trim(preg_replace("/[\s-]+/", " ", $s));
// If a max lenght was specified, trim to that length (trimming space)
if( is_numeric($maxLength) ) {
$s = trim(substr($s, 0, (int)$maxLength));
}
// Replace all spaces with a single hyphen.
$s = preg_replace("/\s/", "-", $s);
return $s;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment