Wednesday, April 08, 2009

Improved c# Slug generator (or how to make friendly url from a post title)

 

here is an improved version of the Slug generator from Kamran Ayub. You can found original post here : http://www.intrepidstudios.com/blog/2009/2/10/function-to-generate-a-url-friendly-string.aspx

I’ve added the ability to remove accent.

public static string GenerateSlug(this string phrase)
{
    string str = phrase.RemoveAccent().ToLower();

    str = Regex.Replace(str, @"[^a-z0-9\s-]", ""); // invalid chars          
   
str = Regex.Replace(str, @"\s+", " ").Trim(); // convert multiple spaces into one space  
   
str = str.Substring(0, str.Length <= 45 ? str.Length : 45).Trim(); // cut and trim it  
   
str = Regex.Replace(str, @"\s", "-"); // hyphens  

   
return str;
}

public static string RemoveAccent(this string txt)
{
    byte[] bytes = System.Text.Encoding.GetEncoding("Cyrillic").GetBytes(txt);
    return System.Text.Encoding.ASCII.GetString(bytes);
}

note: I’ve chosen to implement them as extension method, feel free to modify this.

5 comments:

albi said...

Hi, nice work, simply and useful :) thx

Carlos Fernandes said...

Brilliant! I am from Portugal, and the accents were killing me. Your method is a very clean solution.

Anonymous said...
This comment has been removed by a blog administrator.
Anonymous said...

The author of predicatet.blogspot.com has written an excellent article. You have made your point and there is not much to argue about. It is like the following universal truth that you can not argue with: If you announce a plan that is amusing but harmless, you'll end up with your feet meeting your tonsils Thanks for the info.

Anonymous said...

predicatet.blogspot.com is the best. Thank your for this article. I enjoyed it very much.
AAA Toronto Payday Loans 1172 Bay St #101, Toronto, ON M5S 2B4 (416) 477-2817