Created
June 28, 2011 23:31
-
-
Save borzilleri/1052501 to your computer and use it in GitHub Desktop.
method for generating slugs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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