How does Stack Overflow generate its SEO-friendly URLs?

后端 未结 21 1820
-上瘾入骨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:49

    I am not familiar with Ruby on Rails, but the following is (untested) PHP code. You can probably translate this very quickly to Ruby on Rails if you find it useful.

    $sURL = "This is a title to convert to URL-format. It has 1 number in it!";
    // To lower-case
    $sURL = strtolower($sURL);
    
    // Replace all non-word characters with spaces
    $sURL = preg_replace("/\W+/", " ", $sURL);
    
    // Remove trailing spaces (so we won't end with a separator)
    $sURL = trim($sURL);
    
    // Replace spaces with separators (hyphens)
    $sURL = str_replace(" ", "-", $sURL);
    
    echo $sURL;
    // outputs: this-is-a-title-to-convert-to-url-format-it-has-1-number-in-it
    

    I hope this helps.

提交回复
热议问题