13

假设我有这个网页:
http ://ww.xyz.com/Product.aspx?CategoryId=1

如果 CategoryId=1 的名称是“Dogs”,我想将 URL 转换为如下内容:
http ://ww.xyz.com/Products/Dogs

问题是类别名称是否包含外来(或对 url 无效)字符。如果 CategoryId=2 的名称是“Göra äldre”,那么新的 url 应该是什么?

从逻辑上讲,它应该是:
http: //ww.xyz.com/Products/Göra äldre
但它不起作用。首先是因为空格(例如,我可以很容易地用破折号替换)但是外来字符呢?在 Asp.net 中,我可以使用 URLEncode 函数,它会给出这样的结果:
http
://ww.xyz.com/Products/G%c3%b6ra+%c3%a4ldre 但我真的不能说它比原来的更好网址(http://ww.xyz.com/Product.aspx?CategoryId=2

理想情况下,我想生成这个,但我怎样才能自动执行此操作(即将外来字符转换为“安全”url 字符):
http ://ww.xyz.com/Products/Gora-aldre

4

4 回答 4

34

我想出了以下两种扩展方法(asp.net / C#):

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

    public static string Slugify(this string phrase)
    {
        string str = phrase.RemoveAccent().ToLower();
        str = System.Text.RegularExpressions.Regex.Replace(str, @"[^a-z0-9\s-]", ""); // Remove all non valid chars          
        str = System.Text.RegularExpressions.Regex.Replace(str, @"\s+", " ").Trim(); // convert multiple spaces into one space  
        str = System.Text.RegularExpressions.Regex.Replace(str, @"\s", "-"); // //Replace spaces by dashes
        return str;
    }
于 2010-07-18T12:57:03.593 回答
2

使用如下方式将非 ASCII 字符转译为 ASCII:

var str = "éåäöíØ";
var noApostrophes = Encoding.ASCII.GetString(Encoding.GetEncoding("Cyrillic").GetBytes(str)); 

=> "eaaoiO"

来源

于 2010-07-18T11:04:53.037 回答
2
于 2014-10-08T01:59:47.870 回答
-1

我使用http://www.blackbeltcoder.com/Articles/strings/converting-text-to-a-url-friendly-slug中描述的功能。它不直接支持非英文字符,但可以轻松更新以支持其他字符。

我喜欢它,因为它会产生看起来非常干净的蛞蝓。

于 2010-12-17T06:04:54.723 回答