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

后端 未结 12 1499
再見小時候
再見小時候 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: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?

提交回复
热议问题