How does Stack Overflow generate its SEO-friendly URLs?

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

    For good measure, here's the PHP function in WordPress that does it... I'd think that WordPress is one of the more popular platforms that uses fancy links.

        function sanitize_title_with_dashes($title) {
                $title = strip_tags($title);
                // Preserve escaped octets.
                $title = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '---$1---', $title);
                // Remove percent signs that are not part of an octet.
                $title = str_replace('%', '', $title);
                // Restore octets.
                $title = preg_replace('|---([a-fA-F0-9][a-fA-F0-9])---|', '%$1', $title);
                $title = remove_accents($title);
                if (seems_utf8($title)) {
                        if (function_exists('mb_strtolower')) {
                                $title = mb_strtolower($title, 'UTF-8');
                        }
                        $title = utf8_uri_encode($title, 200);
                }
                $title = strtolower($title);
                $title = preg_replace('/&.+?;/', '', $title); // kill entities
                $title = preg_replace('/[^%a-z0-9 _-]/', '', $title);
                $title = preg_replace('/\s+/', '-', $title);
                $title = preg_replace('|-+|', '-', $title);
                $title = trim($title, '-');
                return $title;
        }
    

    This function as well as some of the supporting functions can be found in wp-includes/formatting.php.

提交回复
热议问题