code_junkie

How do I generate a Friendly URL in C#?

Nov 10th, 2011
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.75 KB | None | 0 0
  1. if (String.IsNullOrEmpty(title)) return "";
  2.  
  3. // remove any leading or trailing spaces left over
  4. … muuuch later:
  5. // remove trailing dash, if there is one
  6.  
  7. // replace spaces with single dash
  8. title = Regex.Replace(title, @"s+", "-");
  9. // if we end up with multiple dashes, collapse to single dash
  10. title = Regex.Replace(title, @"-{2,}", "-");
  11.  
  12. // make it all lower case
  13. title = title.ToLower();
  14. // remove entities
  15. title = Regex.Replace(title, @"&w+;", "");
  16. // remove anything that is not letters, numbers, dash, or space
  17. title = Regex.Replace(title, @"[^a-z0-9-s]", "");
  18. // replace spaces
  19. title = title.Replace(' ', '-');
  20. // collapse dashes
  21. title = Regex.Replace(title, @"-{2,}", "-");
  22. // trim excessive dashes at the beginning
  23. title = title.TrimStart(new [] {'-'});
  24. // if it's too long, clip it
  25. if (title.Length > 80)
  26. title = title.Substring(0, 79);
  27. // remove trailing dashes
  28. title = title.TrimEnd(new [] {'-'});
  29. return title;
  30.  
  31. if (String.IsNullOrEmpty(title)) return "";
  32.  
  33. // remove entities
  34. title = Regex.Replace(title, @"&w+;", "");
  35. // remove anything that is not letters, numbers, dash, or space
  36. title = Regex.Replace(title, @"[^A-Za-z0-9-s]", "");
  37. // remove any leading or trailing spaces left over
  38. title = title.Trim();
  39. // replace spaces with single dash
  40. title = Regex.Replace(title, @"s+", "-");
  41. // if we end up with multiple dashes, collapse to single dash
  42. title = Regex.Replace(title, @"-{2,}", "-");
  43. // make it all lower case
  44. title = title.ToLower();
  45. // if it's too long, clip it
  46. if (title.Length > 80)
  47. title = title.Substring(0, 79);
  48. // remove trailing dash, if there is one
  49. if (title.EndsWith("-"))
  50. title = title.Substring(0, title.Length - 1);
  51. return title;
  52.  
  53. new Regex("[^a-zA-Z-_]").Replace(s, "-")
  54.  
  55. a = a.Replace(' ', '-');
Add Comment
Please, Sign In to add comment