小编典典

C#中的URL Slugify算法?

c#

因此,我搜索并浏览了SO上的slug标签,仅发现两个引人注目的解决方案:

这只是该问题的部分解决方案。我可以自己手动编写此代码,但令我感到惊讶的是,目前还没有解决方案。

那么,在C#和/或.NET中是否有一个迟钝的算法实现,可以正确解决拉丁字符,unicode和其他各种语言问题?


阅读 322

收藏
2020-05-19

共1个答案

小编典典

http://predicatet.blogspot.com/2009/04/improved-c-slug-generator-or-how-
to.html

public static string GenerateSlug(this string phrase) 
{ 
    string str = phrase.RemoveAccent().ToLower(); 
    // invalid chars           
    str = Regex.Replace(str, @"[^a-z0-9\s-]", ""); 
    // convert multiple spaces into one space   
    str = Regex.Replace(str, @"\s+", " ").Trim(); 
    // cut and trim 
    str = str.Substring(0, str.Length <= 45 ? str.Length : 45).Trim();   
    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); 
}
2020-05-19