从 url 中删除多余的破折号

Remove extra dash from url

我有一个博客系统,用户可以在其中输入标题,然后我从中创建 url 这里是创建 url

的函数
function create_slug($string){     
    $replace = '-';         
    $string = strtolower($string);     

    //replace / and . with white space     
    $string = preg_replace("/[\/\.]/", " ", $string);     
    $string = preg_replace("/[^a-z0-9_\s-]/", "", $string);     

    //remove multiple dashes or whitespaces     
    $string = preg_replace("/[\s-]+/", " ", $string);     

    //convert whitespaces and underscore to $replace     
    $string = preg_replace("/[\s_]/", $replace, $string);     

    //limit the slug size     
    $string = substr($string, 0, 100);     

    //slug is generated     
    return $string; 
}    

如果用户输入标题 "hello how are you" 然后它变成 "hello-how-are-you"!

现在我面临的问题是,如果用户在 "you " 之后给出额外的 space,那么它将变成 "hello-how-are-you-"。 如何避免这个额外的破折号?

您要做的是为标题创建 slug。这是相同的link

就像 Rizier123 说 trim() 会删除输入值前后的空格,不要忘记在用破折号替换所有空格之前必须 trim()

因为:

trim() 将从 "hello how are you " => "hello how are you"

但从 "hello-how-are-you-" 开始,它将使 "hello-how-are-you-"