Skip to content

Instantly share code, notes, and snippets.

@kamranayub
Created March 4, 2011 00:26
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kamranayub/853906 to your computer and use it in GitHub Desktop.
Save kamranayub/853906 to your computer and use it in GitHub Desktop.
Generates a URL-friendly "slug" from an unsanitized string
/// <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
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