How can I create a SEO friendly dash-delimited url

2019-01-14 12:29发布

Take a string such as:

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

and convert it to:

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

Requirements:

  • 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?

12条回答
smile是对你的礼貌
2楼-- · 2019-01-14 12:38

In a dynamic URL, these IDs are passed via the query string to a script that ... as the delimiting character because most search engines treat the dash as a ... NET: A Developer's Guide to SEO also covers these three additional methods search engine optimization

查看更多
3楼-- · 2019-01-14 12:39

C#

public string toFriendly(string subject)
{
    subject = subject.Trim().ToLower();
    subject = Regex.Replace(subject, @"\s+", "-");
    subject = Regex.Replace(subject, @"[^A-Za-z0-9_-]", "");
    return subject;
}
查看更多
Ridiculous、
4楼-- · 2019-01-14 12:39

Solution in shell:

echo 'In C#: How do I add "Quotes" around string in a comma delimited list of strings?' | \
    tr A-Z a-z | \
    sed 's/[^a-z0-9]\+/-/g;s/^\(.\{1,20\}\).*/\1/'
查看更多
一纸荒年 Trace。
5楼-- · 2019-01-14 12:41

Solution in Perl:

my $input = 'In C#: How do I add "Quotes" around string in a comma delimited list of strings?';

my $length = 20;
$input =~ s/[^a-z0-9]+/-/gi;
$input =~ s/^(.{1,$length}).*/\L$1/;

print "$input\n";

done.

查看更多
唯我独甜
6楼-- · 2019-01-14 12:41

In python, (if django is installed, even if you are using another framework.)

from django.template.defaultfilters import slugify
slugify("In C#: How do I add "Quotes" around string in a comma delimited list of strings?")
查看更多
手持菜刀,她持情操
7楼-- · 2019-01-14 12:48

A better version:

function Slugify($string)
{
    return strtolower(trim(preg_replace(array('~[^0-9a-z]~i', '~-+~'), '-', $string), '-'));
}
查看更多
登录 后发表回答