我如何在C#中生成一个友好的URL?

问题描述 投票:28回答:4

我该如何在C#中生成一个友好的URL?当前,我简单地用下划线替换空格,但是如何生成类似Stack Overflow的URL?

例如,如何转换:

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

进入

如何在C中生成友好的网址

c# friendly-url
4个回答
47
投票

但是,Jeff的解决方案中有几处可以改进。

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;

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


18
投票

这是我们的操作方式。请注意,边缘条件可能比您乍看之下要多。.


5
投票

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


0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.