如何在C#中生成友好URL?目前我简单地用下划线替换空格,但是我如何生成像Stack Overflow这样的URL呢?
例如,我如何转换:
如何在C#中生成友好URL?
成
怎么办 - 我 - 产生 - 一个友好的URL,在-C
Kon*_*lph 47
但是,Jeff的解决方案有几个方面可以改进.
if (String.IsNullOrEmpty(title)) return "";
Run Code Online (Sandbox Code Playgroud)
恕我直言,不是测试这个的地方.如果函数传递一个空字符串,那么无论如何都会出现严重错误.抛出错误或根本不做出反应.
// remove any leading or trailing spaces left over
… muuuch later:
// remove trailing dash, if there is one
Run Code Online (Sandbox Code Playgroud)
两次工作.考虑到每个操作都会创建一个全新的字符串,这很糟糕,即使性能不是问题.
// 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,}", "-");
Run Code Online (Sandbox Code Playgroud)
同样,基本上是两倍的工作:首先,使用正则表达式一次替换多个空格.然后,再次使用regex一次替换多个破折号.解析两个表达式,在内存中构造两个自动机,在字符串上迭代两次,创建两个字符串:所有这些操作都可以折叠为一个.
在我的头顶,没有任何测试,这将是一个等效的解决方案:
// 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;
Run Code Online (Sandbox Code Playgroud)
请注意,此方法尽可能使用字符串函数而不是正则函数和char函数而不是字符串函数.
Jef*_*ood 18
这是我们如何做到的.请注意,乍看之下可能存在比边缘条件更多的边缘条件.
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;
Run Code Online (Sandbox Code Playgroud)
这是其中的一部分(使用有效字符的白名单):
new Regex("[^a-zA-Z-_]").Replace(s, "-")
Run Code Online (Sandbox Code Playgroud)
但是,它确实为您提供了以“-”结尾的字符串。因此,也许要使用第二个正则表达式来从字符串的开头/结尾修剪掉它们,并可能将任何内部的“-”替换为“-”。