如何从字符串创建SEO友好的短划线分隔网址? [英] How can I create a SEO friendly dash-delimited url from a string?

查看:76
本文介绍了如何从字符串创建SEO友好的短划线分隔网址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

采用一个字符串,例如:

Take a string such as:

在C#中:如何在逗号分隔的字符串列表中的字符串周围添加引号"?

In C#: How do I add "Quotes" around string in a comma delimited list of strings?

并将其转换为:

C如何在逗号分隔的字符串列表中添加围绕字符串的报价

in-c-how-do-i-add-quotes-around-string-in-a-comma-delimited-list-of-strings

要求:

  • 用破折号分隔每个单词,并删除所有标点符号(考虑到并非所有单词都用空格分隔.)
  • 函数采用最大长度,并获得小于该最大长度的所有令牌.示例:ToSeoFriendly("hello world hello world", 14)返回"hello-world"
  • 所有单词都转换为小写.
  • Separate each word by a dash and remove all punctuation (taking into account not all words are separated by spaces.)
  • Function takes in a max length, and gets all tokens below that max length. Example: ToSeoFriendly("hello world hello world", 14) returns "hello-world"
  • All words are converted to lower case.

另外,应该有一个最小长度吗?

On a separate note, should there be a minimum length?

推荐答案

这是我在C#中的解决方案

Here is my solution in C#

private string ToSeoFriendly(string title, int maxLength) {
    var match = Regex.Match(title.ToLower(), "[\\w]+");
    StringBuilder result = new StringBuilder("");
    bool maxLengthHit = false;
    while (match.Success && !maxLengthHit) {
        if (result.Length + match.Value.Length <= maxLength) {
            result.Append(match.Value + "-");
        } else {
            maxLengthHit = true;
            // Handle a situation where there is only one word and it is greater than the max length.
            if (result.Length == 0) result.Append(match.Value.Substring(0, maxLength));
        }
        match = match.NextMatch();
    }
    // Remove trailing '-'
    if (result[result.Length - 1] == '-') result.Remove(result.Length - 1, 1);
    return result.ToString();
}

这篇关于如何从字符串创建SEO友好的短划线分隔网址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆