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

后端 未结 12 1531
再見小時候
再見小時候 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;
    }
    

提交回复
热议问题