Best way to remove trailing slashes in URLs with PHP

前端 未结 4 2087
广开言路
广开言路 2021-01-31 07:40

I have some URLs, like www.amazon.com/, www.digg.com or www.microsoft.com/ and I want to remove the trailing slash, if it exists, so not j

相关标签:
4条回答
  • 2021-01-31 07:48

    You put rtrim in your answer, why not just look it up?

    $url = rtrim($url,"/");
    

    As a side note, look up any PHP function by doing the following:

    • http://php.net/functionname
    • http://php.net/rtrim
    • http://php.net/trim

    (rtrim stands for 'Right trim')

    0 讨论(0)
  • 2021-01-31 07:51

    I came here looking for a way to remove trailing slash and redirect the browser, I have come up with an answer that I would like to share for anyone coming after me:

    //remove trailing slash from uri
    if( ($_SERVER['REQUEST_URI'] != "/") and preg_match('{/$}',$_SERVER['REQUEST_URI']) ) {
        header ('Location: '.preg_replace('{/$}', '', $_SERVER['REQUEST_URI']));
        exit();
    }
    

    The ($_SERVER['REQUEST_URI'] != "/") will avoid host URI e.g www.amazon.com/ because web browsers always send a trailing slash after a domain name, and preg_match('{/$}',$_SERVER['REQUEST_URI']) will match all other URI with trailing slash as last character. Then preg_replace('{/$}', '', $_SERVER['REQUEST_URI']) will remove the slash and hand over to header() to redirect. The exit() function is important to stop any further code execution.

    0 讨论(0)
  • 2021-01-31 07:52
    $urls="www.amazon.com/ www.digg.com/ www.microsoft.com/";
    echo preg_replace("/\b\//","",$urls);
    
    0 讨论(0)
  • 2021-01-31 08:01

    Simple and works across both Windows and Unix:

    $url = rtrim($url, '/\\')
    
    0 讨论(0)
提交回复
热议问题