C# 中的 URL Slugify 算法?
因此,我搜索并浏览了 SO 上的 slug 标签,只找到了两个引人注目的解决方案:
这只是问题的部分解决方案。我可以自己手动编写代码,但令我惊讶的是还没有解决方案。
那么,C# 和/或 .NET 中是否有一个 slugify 算法实现可以正确解决拉丁字符、unicode 和各种其他语言问题?
So I have searched and browsed through the slug tag on SO and only found two compelling solution:
Which are but partial solution to the problem. I could manually code this up myself but I'm surprised that there isn't already a solution out there yet.
So, is there a slugify alrogithm implementation in C# and/or .NET that properly address latin characters, unicode and various other language issues properly?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
http://predicatet.blogspot.com /2009/04/improved-c-slug-generator-or-how-to.html
http://predicatet.blogspot.com/2009/04/improved-c-slug-generator-or-how-to.html
在这里您可以找到一种在 C# 中生成 url slug 的方法。此函数删除所有重音符号(马塞尔的答案),替换空格,删除无效字符,从末尾修剪破折号并替换重复出现的“-”或“_”
代码:
Here you find a way to generate url slug in c#. This function remove all accents(Marcel's answer), replace spaces, remove invalid chars, trim dashes from end and replace double occurences of "-" or "_"
Code:
这是我的演绎,基于琼和马塞尔的答案。我所做的更改如下:
这是代码:
这仍然没有解决非拉丁字符问题。完全替代的解决方案是使用 Uri.EscapeDataString将字符串转换为十六进制表示:
然后使用数据生成超链接:
很多浏览器都会在地址栏中显示汉字(见下文),但根据我有限的测试,并不完全支持。
注意:为了 Uri.EscapeDataString 以这种方式工作,iriParsing 必须启用。
编辑
对于那些希望在 C# 中生成 URL Slug 的人,我建议查看此相关问题:
Stack Overflow 如何生成 SEO 友好的 URL?
这是我最终在我的项目中使用的。
Here is my rendition, based Joan's and Marcel's answers. The changes I made are as follows:
Here is the code:
This still does not solve the non-latin character issue. A completely alternative solution would be to use Uri.EscapeDataString to convert the the string its hex representation:
Then use the data to generate a hyperlink:
Many browsers will display Chinese characters in the address bar (see below), but based on my limited testing, it is not completely supported.
NOTE: In order for Uri.EscapeDataString to work this way, iriParsing must be enabled.
EDIT
For those looking to generate URL Slugs in C#, I recommend checking out this related question:
How does Stack Overflow generate its SEO-friendly URLs?
It is what I ended up using for my project.
我在slugification(新词!)方面遇到的一个问题是冲突。例如,如果我有一篇名为“Stack-Overflow”的博客文章和一篇名为“Stack Overflow”的博客文章,那么这两个标题的标题是相同的。因此,我的 slug 生成器通常必须以某种方式涉及数据库。这可能就是为什么您看不到更多通用解决方案的原因。
One problem I've had with slugification (new word!) is collisions. If I have a blog post, for instance, called "Stack-Overflow" and one called "Stack Overflow", the slugs of those two titles are the same. Therefore, my slug generator usually has to involve the database in some way. This might be why you don't see more generic solutions out there.
这是我的尝试。它支持:
代码:
Here is my shot at it. It supports:
Code: