Created
March 4, 2011 00:26
-
-
Save kamranayub/853906 to your computer and use it in GitHub Desktop.
Generates a URL-friendly "slug" from an unsanitized string
This file contains hidden or 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
/// <summary> | |
/// Will transform "some $ugly ###url wit[]h spaces" into "some-ugly-url-with-spaces" | |
/// </summary> | |
public static string Slugify(this string phrase, int maxLength = 50) | |
{ | |
string str = phrase.ToLower(); | |
// invalid chars, make into spaces | |
str = Regex.Replace(str, @"[^a-z0-9\s-]", ""); | |
// convert multiple spaces/hyphens into one space | |
str = Regex.Replace(str, @"[\s-]+", " ").Trim(); | |
// cut and trim it | |
str = str.Substring(0, str.Length <= maxLength ? str.Length : maxLength).Trim(); | |
// hyphens | |
str = Regex.Replace(str, @"\s", "-"); | |
return str; | |
} | |
// slug | |
string title = @"A bunch of ()/*++\'#@$&*^!% invalid URL characters "; | |
return title.Slugify(); | |
// outputs | |
a-bunch-of-invalid-url-characters |
This file contains hidden or 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
function generateSlug($phrase, $maxLength) | |
{ | |
$result = strtolower($phrase); | |
$result = preg_replace("/[^a-z0-9\s-]/", "", $result); | |
$result = trim(preg_replace("/[\s-]+/", " ", $result)); | |
$result = trim(substr($result, 0, $maxLength)); | |
$result = preg_replace("/\s/", "-", $result); | |
return $result; | |
} | |
$title = "A bunch of ()/*++\'#@$&*^!% invalid URL characters "; | |
echo(generateSlug($title)); | |
// outputs | |
a-bunch-of-invalid-url-characters |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment