tags:

views:

236

answers:

3

So I have searched and browsed through the slug tag on SO and only found two compelling solution:

Which are but partial solution to the problem. I could manually code this up myself but I'm surprised that there isn't already a solution out there yet.

So, is there a slugify alrogithm implementation in C# and/or .NET that properly address latin characters, unicode and various other language issues properly?

A: 

The "algorithm" I've seen sofar is just the use of a table of from/to replacements, and a way to filter out the remaining characters (for instance, the entire chinese "alphabet").

If you use Encoding.ASCII.GetString(Encoding.ASCII.GetBytes(unicodeString)), you'll filter out any character except the base ASCII characters. Other characters get converted to question marks. Something like this:

Dictionary<char, char> lReplaceValues = new Dictionary<char, char>();
lReplaceValues['ä'] = 'a';
lReplaceValues['ö'] = 'o';
lReplaceValues['ë'] = 'e';

string lSlug = "Hëllö wórld!";
foreach (KeyValuePair<char, char> lReplaceValue in lReplaceValues)
{
    lSlug = lSlug.Replace(lReplaceValue.Key, lReplaceValue.Value);
}
lSlug = Encoding.ASCII.GetString(Encoding.ASCII.GetBytes(lSlug));

There has to be a more elegant way, btw.

deltreme
That's not slugifying.. That's character replacement."Hello world" as a slug would be "hello-world".
Ian P
+5  A: 

http://predicatet.blogspot.com/2009/04/improved-c-slug-generator-or-how-to.html

Marcel
The link posted satisfies the OP's question nicely.
Ian P
+2  A: 

One problem I've had with slugification (new word!) is collisions. If I have a blog post, for instance, called "Stack-Overflow" and one called "Stack Overflow", the slugs of those two titles are the same. Therefore, my slug generator usually has to involve the database in some way. This might be why you don't see more generic solutions out there.

mgroves
Personally I prefer to append slugs with an unique identifier (ie an integer) to make sure they are unique. It's not the friendliest solution but it helps me to steer clear of trouble.
Jeremy