Is it possible to remove the trailing slash / from a string using PHP?
5 Answers
Sure it is, simply check if the last character is a slash and then nuke that one.
if(substr($string, -1) == '/') {
$string = substr($string, 0, -1);
}
Another (probably better) option would be using rtrim() - this one removes all trailing slashes:
$string = rtrim($string, '/');
5 Comments
Brad
I'd also suggest using
DIRECTORY_SEPARATOR instead of '/' if using file paths so it works on all platforms.Toxiro
You cannot use
DIRECTORY_SEPARATOR, because windows paths can use both \ and /.Brad
DIRECTORY_SEPARATOR is a reference to what the OS uses as a directory separator. No system uses both ever.
Toxiro
@Brad file paths do not need to come from the OS itself, they can come from user input, from config files, from hard coded paths in your code or from external libraries. And they mostly use just
/ and DO work in windows. If you also use paths from the OS you have mixed paths with both slashes and they both work in Windows. So, if you want to join those paths you have to be aware that in Windows you need to trim both slashes while in Linux you ONLY have to trim /, because the backslash is a normal character like letters in Linux paths.Brad
Good point! Id recommend trimming both slashes then.
This removes trailing slashes:
$str = rtrim($str, '/');
1 Comment
Gumbo
Note that this removes all trailing slashes.
Long accepted, however in my related searches I stumbled here, and am adding for "completeness"; rtrim() is great, however implemented like this:
$string = rtrim($string, '/\\'); //strip both forward and back slashes
It ensures portability from *nix to Windows, as I assume this question pertains to dealing with paths.
8 Comments
Félix Adriyel Gagnon-Grenier
interesting! however on my end I stumbled here regarding routes, not paths
Dan Lugg
@FélixGagnon-Grenier Well, the answer is somewhat presumptuous with concern to paths; the OP may have had altogether different reasons. Since "routes" typically act on "paths" (of some sort) it's all the same in the end :-)
Jens
In case the Op would indeed want to remove a trailing directory separator from a path, use the constant
DIRECTORY_SEPARATOR instead of '/\\'.Toxiro
You cannot use
DIRECTORY_SEPARATOR, because windows paths can use both \ and /.Dan Lugg
@Jens I'd agree, however since PHP supports *nix and Windows paths corner cases might go untrimmed.
Jens
@NorthbornDesign: Do you have an example? You mean trimming a *nix path on Windows, and vice versa, not just native paths?
|
2 Comments
user502515
Except that it does not really remove trailing slashes, but unquotes a string.
Breezer
well i missed the trailing part in the question... I made a mistake and i specifically wrote that it removes all slashes