我找不到任何像 Ruby 中那样的库来完成它,所以最终我自己编写了一个方法。如果有人感兴趣,这就是它:
public static string ForUrl(this string str) {
return str.ForUrl(true);
}
public static string ForUrl(this string str, bool MakeLowerCase) {
if (MakeLowerCase) {
str = str.ToLower();
}
char[] from = "ÂÃÄÀÁÅÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝàáâãäåçèéêëìíîïðñòóôõöøùúûüýÿ".ToCharArray();
char[] to = "AAAAAACEEEEIIIIDNOOOOOOUUUUYaaaaaaceeeeiiiidnoooooouuuuyy".ToCharArray();
for (int i = 0; i < from.Length; i++) {
str = str.Replace(from[i], to[i]);
}
str = str.Replace("Þ", "TH");
str = str.Replace("þ", "th");
str = str.Replace("ß", "ss");
str = str.Replace("Æ", "AE");
str = str.Replace("æ", "ae");
from = "ĈĜĤĴŜŬĉĝĥĵŝŭ".ToCharArray();
to = "CXGXHXJXSXUXcxgxhxjxsxux".ToCharArray();
for (int i = 0; i < from.Length; i++) {
str = str.Replace(from[i].ToString(), "{0}{1}".Args(to[i*2], to[i*2+1]));
}
str = new Regex(@"([¢€£\$])([0-9\.,]+)").Replace(str, @"$2 $1");
str = str.Replace("¢", "cents");
str = str.Replace("€", "euros");
str = str.Replace("£", "pounds");
str = str.Replace("$", "dollars");
str = str.Replace("&", " and ");
str = str.Replace("'", "");
str = str.Replace("’", "");
str = new Regex(@"[^A-Za-z0-9-]").Replace(str, "-");
str = str.Trim("-".ToCharArray());
str = new Regex("-+").Replace(str, "-");
return str.UrlEncode();
}