Remove Trailing Slash From String PHP

PhpString

Php Problem Overview


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

Php Solutions


Solution 1 - Php

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

Solution 2 - Php

This removes trailing slashes:

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

Solution 3 - Php

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.

Solution 4 - Php

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

Solution 5 - Php

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionZac BrownView Question on Stackoverflow
Solution 1 - PhpThiefMasterView Answer on Stackoverflow
Solution 2 - PhpRossView Answer on Stackoverflow
Solution 3 - PhpDan LuggView Answer on Stackoverflow
Solution 4 - PhpBreezerView Answer on Stackoverflow
Solution 5 - Phpuser187291View Answer on Stackoverflow