How can I create a SEO friendly dash-delimited url from a string?

后端 未结 12 1501
再見小時候
再見小時候 2020-12-05 19:16

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:

相关标签:
12条回答
  • 2020-12-05 20:04

    I would follow these steps:

    1. convert string to lower case
    2. replace unwanted characters by hyphens
    3. replace multiple hyphens by one hyphen (not necessary as the preg_replace() function call already prevents multiple hyphens)
    4. remove hypens at the begin and end if necessary
    5. trim if needed from the last hyphen before position x to the end

    So, all together in a function (PHP):

    function generateUrlSlug($string, $maxlen=0)
    {
        $string = trim(preg_replace('/[^a-z0-9]+/', '-', strtolower($string)), '-');
        if ($maxlen && strlen($string) > $maxlen) {
            $string = substr($string, 0, $maxlen);
            $pos = strrpos($string, '-');
            if ($pos > 0) {
                $string = substr($string, 0, $pos);
            }
        }
        return $string;
    }
    
    0 讨论(0)
  • 2020-12-05 20:05

    This is close to how Stack Overflow generates slugs:

    public static string GenerateSlug(string title)
    {
        string slug = title.ToLower();
        if (slug.Length > 81)
          slug = slug.Substring(0, 81);
        slug = Regex.Replace(slug, @"[^a-z0-9\-_\./\\ ]+", "");
        slug = Regex.Replace(slug, @"[^a-z0-9]+", "-");
    
        if (slug[slug.Length - 1] == '-')
          slug = slug.Remove(slug.Length - 1, 1);
        return slug;
    }
    
    0 讨论(0)
  • 2020-12-05 20:05

    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?")
    
    0 讨论(0)
  • 2020-12-05 20:06

    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/'
    
    0 讨论(0)
  • 2020-12-05 20:06

    A slightly cleaner way of doing this in PHP at least is:

    function CleanForUrl($urlPart, $maxLength = null) {
        $url = strtolower(preg_replace(array('/[^a-z0-9\- ]/i', '/[ \-]+/'), array('', '-'), trim($urlPart)));
        if ($maxLength) $url = substr($url, 0, $maxLength);
        return $url;
    }
    

    Might as well do the trim() at the start so there is less to process later and the full replacement is done with in the preg_replace().

    Thxs to cg for coming up with most of this: What is the best way to clean a string for placement in a URL, like the question name on SO?

    0 讨论(0)
  • 2020-12-05 20:10

    A better version:

    function Slugify($string)
    {
        return strtolower(trim(preg_replace(array('~[^0-9a-z]~i', '~-+~'), '-', $string), '-'));
    }
    
    0 讨论(0)
提交回复
热议问题