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?
4 Answers
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')
Simple and works across both Windows and Unix:
$url = rtrim($url, '/\\')
-
1
-
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. Oct 11, 2019 at 20:14
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.
-
Yes good way for clean the extra Backslash "/" from URL but when i that put extra Backslash in front of url,it is crashing– AminApr 7, 2020 at 16:16
$urls="www.amazon.com/ www.digg.com/ www.microsoft.com/";
echo preg_replace("/\b\//","",$urls);
-
10
-
Besides, the RE would fail pretty nicely for URLs that also contain slashes in the middle.– JoeyMar 6, 2010 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. Sep 27, 2012 at 4: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.– trejderSep 23, 2013 at 8:28