如何在 C# 中生成友好 URL?

发布于 2024-10-20 11:38:30 字数 213 浏览 9 评论 0原文

如何在 C# 中生成友好 URL?目前,我简单地将空格替换为下划线,但是我将如何生成像 Stack Overflow 一样的 URL?

例如我如何转换:

如何在 C# 中生成友好 URL?

进入

如何在 C 语言中生成友好的 url

How can I go about generating a Friendly URL in C#? Currently I simple replace spaces with an underscore, but how would I go about generating URL's like Stack Overflow?

For example how can I convert:

How do I generate a Friendly URL in C#?

Into

how-do-i-generate-a-friendly-url-in-C

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

三生池水覆流年 2024-10-27 11:38:30

不过,杰夫的解决方案中有几处可以改进的地方。

if (String.IsNullOrEmpty(title)) return "";

恕我直言,不是测试这个的地方。如果函数传递一个空字符串,无论如何都会出现严重错误。抛出错误或者根本不做出反应。

// remove any leading or trailing spaces left over
… muuuch later:
// remove trailing dash, if there is one

工作量加倍。考虑到每个操作都会创建一个全新的字符串,这很糟糕,即使性能不是问题。

// replace spaces with single dash
title = Regex.Replace(title, @"\s+", "-");
// if we end up with multiple dashes, collapse to single dash            
title = Regex.Replace(title, @"\-{2,}", "-");

同样,基本上是两倍的工作:首先,使用正则表达式一次替换多个空格。然后,再次使用正则表达式一次替换多个破折号。要解析的两个表达式、在内存中构造的两个自动机、在字符串上迭代两次、创建两个字符串:所有这些操作都可以折叠为一个操作。

在我的脑海中,无需任何测试,这将是一个等效的解决方案:

// make it all lower case
title = title.ToLower();
// remove entities
title = Regex.Replace(title, @"&\w+;", "");
// remove anything that is not letters, numbers, dash, or space
title = Regex.Replace(title, @"[^a-z0-9\-\s]", "");
// replace spaces
title = title.Replace(' ', '-');
// collapse dashes
title = Regex.Replace(title, @"-{2,}", "-");
// trim excessive dashes at the beginning
title = title.TrimStart(new [] {'-'});
// if it's too long, clip it
if (title.Length > 80)
    title = title.Substring(0, 79);
// remove trailing dashes
title = title.TrimEnd(new [] {'-'});
return title;

请注意,此方法尽可能使用字符串函数而不是正则表达式函数,使用字符函数而不是字符串函数。

There are several things that could be improved in Jeff's solution, though.

if (String.IsNullOrEmpty(title)) return "";

IMHO, not the place to test this. If the function gets passed an empty string, something went seriously wrong anyway. Throw an error or don't react at all.

// remove any leading or trailing spaces left over
… muuuch later:
// remove trailing dash, if there is one

Twice the work. Considering that each operation creates a whole new string, this is bad, even if performance is not an issue.

// replace spaces with single dash
title = Regex.Replace(title, @"\s+", "-");
// if we end up with multiple dashes, collapse to single dash            
title = Regex.Replace(title, @"\-{2,}", "-");

Again, basically twice the work: First, use regex to replace multiple spaces at once. Then, use regex again to replace multiple dashes at once. Two expressions to parse, two automata to construct in memory, iterate twice over the string, create two strings: All these operations can be collapsed to a single one.

Off the top of my head, without any testing whatsoever, this would be an equivalent solution:

// make it all lower case
title = title.ToLower();
// remove entities
title = Regex.Replace(title, @"&\w+;", "");
// remove anything that is not letters, numbers, dash, or space
title = Regex.Replace(title, @"[^a-z0-9\-\s]", "");
// replace spaces
title = title.Replace(' ', '-');
// collapse dashes
title = Regex.Replace(title, @"-{2,}", "-");
// trim excessive dashes at the beginning
title = title.TrimStart(new [] {'-'});
// if it's too long, clip it
if (title.Length > 80)
    title = title.Substring(0, 79);
// remove trailing dashes
title = title.TrimEnd(new [] {'-'});
return title;

Notice that this method uses string functions instead of regex functions and char functions instead of string functions whenever possible.

多情出卖 2024-10-27 11:38:30

我们是这样做的。请注意,边缘条件可能比您乍一看意识到的要多。

if (String.IsNullOrEmpty(title)) return "";

// remove entities
title = Regex.Replace(title, @"&\w+;", "");
// remove anything that is not letters, numbers, dash, or space
title = Regex.Replace(title, @"[^A-Za-z0-9\-\s]", "");
// remove any leading or trailing spaces left over
title = title.Trim();
// replace spaces with single dash
title = Regex.Replace(title, @"\s+", "-");
// if we end up with multiple dashes, collapse to single dash            
title = Regex.Replace(title, @"\-{2,}", "-");
// make it all lower case
title = title.ToLower();
// if it's too long, clip it
if (title.Length > 80)
    title = title.Substring(0, 79);
// remove trailing dash, if there is one
if (title.EndsWith("-"))
    title = title.Substring(0, title.Length - 1);
return title;

Here's how we do it. Note that there are probably more edge conditions than you realize at first glance..

if (String.IsNullOrEmpty(title)) return "";

// remove entities
title = Regex.Replace(title, @"&\w+;", "");
// remove anything that is not letters, numbers, dash, or space
title = Regex.Replace(title, @"[^A-Za-z0-9\-\s]", "");
// remove any leading or trailing spaces left over
title = title.Trim();
// replace spaces with single dash
title = Regex.Replace(title, @"\s+", "-");
// if we end up with multiple dashes, collapse to single dash            
title = Regex.Replace(title, @"\-{2,}", "-");
// make it all lower case
title = title.ToLower();
// if it's too long, clip it
if (title.Length > 80)
    title = title.Substring(0, 79);
// remove trailing dash, if there is one
if (title.EndsWith("-"))
    title = title.Substring(0, title.Length - 1);
return title;
淡淡绿茶香 2024-10-27 11:38:30

这只是其中的一部分(使用有效字符的白名单):

new Regex("[^a-zA-Z-_]").Replace(s, "-")

但是,它确实为您提供了一个以“--”结尾的字符串。因此,也许第二个正则表达式可以从字符串的开头/结尾修剪这些内容,并且可能将任何内部“--”替换为“-”。

This gets part of the way there (using a whitelist of valid characters):

new Regex("[^a-zA-Z-_]").Replace(s, "-")

It does, however, give you a string that ends with "--". So perhaps a second regex to trim those from the beginning/end of the string, and maybe replace any internal "--" to "-".

去了角落 2024-10-27 11:38:30

这是一个简单的函数,可以将字符串转换为 Url,您只需传递标题或字符串,它就会将其转换为用户友好的 Url。

    public static string GenerateUrl(string Url)
    {
        string UrlPeplaceSpecialWords = Regex.Replace(Url, @""|['"",&?%\.!()@$^_+=*:#/\\-]", " ").Trim();
        string RemoveMutipleSpaces = Regex.Replace(UrlPeplaceSpecialWords, @"\s+", " ");
        string ReplaceDashes = RemoveMutipleSpaces.Replace(" ", "-");
        string DuplicateDashesRemove = ReplaceDashes.Replace("--", "-");
        return DuplicateDashesRemove.ToLower();
    }

here is a simple function which can convert your string to Url, you just need to pass title or string it will convert it to user friendly Url.

    public static string GenerateUrl(string Url)
    {
        string UrlPeplaceSpecialWords = Regex.Replace(Url, @""|['"",&?%\.!()@$^_+=*:#/\\-]", " ").Trim();
        string RemoveMutipleSpaces = Regex.Replace(UrlPeplaceSpecialWords, @"\s+", " ");
        string ReplaceDashes = RemoveMutipleSpaces.Replace(" ", "-");
        string DuplicateDashesRemove = ReplaceDashes.Replace("--", "-");
        return DuplicateDashesRemove.ToLower();
    }
十级心震 2024-10-27 11:38:30

我做了一个小型开源项目,用 C# 生成友好的 url (slugs),请参阅: https:/ /github.com/marthijn/Sidio.Text.Slugifyhttps: //www.nuget.org/packages/Sidio.Text.Slugify/

var slugifier = Slugifier.Create();
var slug = slugifier.Slugify("Hello, World!");

I made a small open source project to generate friendly urls (slugs) in C#, see: https://github.com/marthijn/Sidio.Text.Slugify or https://www.nuget.org/packages/Sidio.Text.Slugify/

var slugifier = Slugifier.Create();
var slug = slugifier.Slugify("Hello, World!");
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文