67

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 just the last character. Is there a trim or rtrim for this?

trejder
  • 17,148
  • 27
  • 124
  • 216
daniel
  • 769
  • 1
  • 6
  • 4

4 Answers4

288

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

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

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

(rtrim stands for 'Right trim')

Erik
  • 20,526
  • 8
  • 45
  • 76
13

Simple and works across both Windows and Unix:

$url = rtrim($url, '/\\')
Dario Fumagalli
  • 1,064
  • 1
  • 16
  • 23
  • 1
    why the `/\\ ` instead of `/`? – Seth B Oct 11 '19 at 19:48
  • 3
    @SethB The second parameter is a list of strings to trim. One character is "/", and another is "\". However, in PHP strings, you need to escape forward slashes, which looks like "\\". Therefore: "/\\" or "\\/" would work. – fideloper Oct 11 '19 at 20:14
5

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.

Community
  • 1
  • 1
Kenneth Kaane
  • 91
  • 1
  • 5
  • Yes good way for clean the extra Backslash "/" from URL but when i that put extra Backslash in front of url,it is crashing – Amin Apr 07 '20 at 16:16
-20
$urls="www.amazon.com/ www.digg.com/ www.microsoft.com/";
echo preg_replace("/\b\//","",$urls);
ghostdog74
  • 327,991
  • 56
  • 259
  • 343
  • 10
    No, don't use regex for this. – Richard Knop Mar 06 '10 at 14:51
  • Besides, the RE would fail pretty nicely for URLs that also contain slashes in the middle. – Joey Mar 06 '10 at 16:08
  • There is nothing wrong with this answer. It simply assumes the URLs are concatenated in a string, as opposed to an array. If they're in an array, Erik's answer is better. If they are in a string separated by spaces or line breaks, this is fine. – supertrue Sep 27 '12 at 04:14
  • 2
    @supertrue There is nothing wrong with this answer _except_ the fact, that RE is _awfully slow_ in compare to other string-related functions in PHP! Even PHP.net docs warns, that regular expressions functions should be avoided in favor of simple string-related functions, due to speed and performance issues. – trejder Sep 23 '13 at 08:28