How does Stack Overflow generate its SEO-friendly URLs?

后端 未结 21 1843
-上瘾入骨i
-上瘾入骨i 2020-11-22 04:27

What is a good complete regular expression or some other process that would take the title:

How do you change a title to be part of the URL like Stack

21条回答
  •  北恋
    北恋 (楼主)
    2020-11-22 04:48

    I don't much about Ruby or Rails, but in Perl, this is what I would do:

    my $title = "How do you change a title to be part of the url like Stackoverflow?";
    
    my $url = lc $title;   # Change to lower case and copy to URL.
    $url =~ s/^\s+//g;     # Remove leading spaces.
    $url =~ s/\s+$//g;     # Remove trailing spaces.
    $url =~ s/\s+/\-/g;    # Change one or more spaces to single hyphen.
    $url =~ s/[^\w\-]//g;  # Remove any non-word characters.
    
    print "$title\n$url\n";
    

    I just did a quick test and it seems to work. Hopefully this is relatively easy to translate to Ruby.

提交回复
热议问题