code_junkie

URL Routing: Handling Spaces and Illegal Characters When Creating Friendly URLs

Nov 12th, 2011
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.40 KB | None | 0 0
  1. /article/1/Some_Article_Title_Here
  2. /article/1/Section/5/Section_Title_Here
  3. /section/19023/Section_Title_here ( == above link )
  4.  
  5. http://www.example.com/x/category-name/subcat-name/article-name/348254863
  6.  
  7. Route r = new Route("{country}/{lang}/Article/{id}/{title}/", new NFRouteHandler("OneArticle"));
  8. Route r2 = new Route("{country}/{lang}/Section/{id}-{subid}/{title}/", new NFRouteHandler("ArticlesInSubcategory"));
  9. Route r3 = new Route("{country}/{lang}/Section/{id}/{title}/", new NFRouteHandler("ArticlesByCategory"));
  10.  
  11. private static string anglicized(this string urlpart) {
  12. string before = "àÀâÂäÄáÁéÉèÈêÊëËìÌîÎïÏòÒôÔöÖùÙûÛüÜçÇ’ñ";
  13. string after = "aAaAaAaAeEeEeEeEiIiIiIoOoOoOuUuUuUcC'n";
  14.  
  15. string cleaned = urlpart;
  16.  
  17. for (int i = 0; i < avantConversion.Length; i++ ) {
  18.  
  19. cleaned = Regex.Replace(urlpart, before[i].ToString(), after[i].ToString());
  20. }
  21.  
  22. return cleaned;
  23.  
  24. // Here's some for Spanish : ÁÉÍÑÓÚÜ¡¿áéíñóúü"
  25.  
  26. }
  27.  
  28. string articleTitle = "My Article about café and the letters àâäá";
  29. string cleaned = articleTitle.anglicized();
  30.  
  31. // replace spaces with dashes
  32. cleaned = Regex.Replace( cleaned, "[^A-Za-z0-9- ]", "");
  33.  
  34. // strip all illegal characters like punctuation
  35. cleaned = Regex.Replace( cleaned, " +", "-").ToLower();
  36.  
  37. // returns "my-article-about-cafe-and-the-letters-aaaa"
Add Comment
Please, Sign In to add comment