Generate a url slug
From CodeCodex
A "slug" is a url that is generated given some text (for example, a webpage title) so that the url for a given item is readable for humans.
For example, the url at a store for blue pens, domain/?id=123 could use a slug to make it human readable, domain/blue-pens?id=123 or simply domain/blue-pens
Contents |
Implementations
Java
package util;
import java.text.Normalizer;
import java.text.Normalizer.Form;
import java.util.Locale;
import java.util.regex.Pattern;
public class Slug {
private static final Pattern NONLATIN = Pattern.compile("[^\\w-]");
private static final Pattern WHITESPACE = Pattern.compile("[\\s]");
public String makeSlug(String input) {
String nowhitespace = WHITESPACE.matcher(input).replaceAll("-");
String normalized = Normalizer.normalize(nowhitespace, Form.NFD);
String slug = NONLATIN.matcher(normalized).replaceAll("");
return slug.toLowerCase(Locale.ENGLISH);
}
}
Perl
my $input = 'In C#: How do I add "Quotes" around string in a comma delimited list of strings?';
my $length = 20;
$input =~ s/[^a-z0-9]+/-/gi;
$input =~ s/^(.{1,$length}).*/\L$1/;
print "$input\n";
Ruby
def seo_friendly(str) str.strip.downcase.gsub /\W+/, '-' end
Python
Using django.
from django.template.defaultfilters import slugify
slugify('In C#: How do I add "Quotes" around string in a comma delimited list of strings?')
C#
private string ToSeoFriendly(string title, int maxLength) {
var match = Regex.Match(title.ToLower(), "[\\w]+");
StringBuilder result = new StringBuilder("");
bool maxLengthHit = false;
while (match.Success && !maxLengthHit) {
if (result.Length + match.Value.Length <= maxLength) {
result.Append(match.Value + "-");
} else {
maxLengthHit = true;
// Handle a situation where there is only one word and it is greater than the max length.
if (result.Length == 0) result.Append(match.Value.Substring(0, maxLength));
}
match = match.NextMatch();
}
// Remove trailing '-'
if (result[result.Length - 1] == '-') result.Remove(result.Length - 1, 1);
return result.ToString();
}
PHP
function generateUrlSlug($string, $maxlen=0)
{
$string = trim(preg_replace('/[^a-z0-9]+/', '-', strtolower($string)), '-');
if ($maxlen && strlen($string) > $maxlen) {
$string = substr($string, 0, $maxlen);
$pos = strrpos($string, '-');
if ($pos > 0) {
$string = substr($string, 0, $pos);
}
}
return $string;
}