Zac Brown
Zac Brown

Reputation: 6063

Remove Trailing Slash From String PHP

Is it possible to remove the trailing slash / from a string using PHP?

Upvotes: 129

Views: 99776

Answers (5)

Ross
Ross

Reputation: 17967

This removes trailing slashes:

$str = rtrim($str, '/');

Upvotes: 73

ThiefMaster
ThiefMaster

Reputation: 318468

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, '/');

Upvotes: 274

Dan Lugg
Dan Lugg

Reputation: 20592

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.

Upvotes: 31

Breezer
Breezer

Reputation: 10490

rtrim Use rtrim cause it respects the string doesnt end with a trailing slash

Upvotes: 6

user187291
user187291

Reputation: 53940

Yes, it is!

http://php.net/manual/en/function.rtrim.php

Upvotes: 3

Related Questions