Add ending slash

Adds an ending slash to the given path, makes a difference
between windows and unix paths (keeps orginal slashes)
The normalize_path function is also a good way for doing this...

function add_ending_slash($path){
 
    $slash_type = (strpos($path, '\\')===0) ? 'win' : 'unix'; 
 
    $last_char = substr($path, strlen($path)-1, 1);
 
    if ($last_char != '/' and $last_char != '\\') {
        // no slash:
        $path .= ($slash_type == 'win') ? '\\' : '/';
    }
 
    return $path;
}
Snippet Details



print add_ending_slash(dirname(__FILE__));
// returns 'c:\my_path\htdocs\codedump\'
 
print add_ending_slash('/foo/bar/hd');
// returns '/foo/bar/hd/'
 
print add_ending_slash('/foo/has_a_slash/hd/');
// returns '/foo/has_a_slash/hd/'
 
print add_ending_slash('c:/files');
// returns 'c:/files/'

Sorry folks, comments have been deactivated for now due to the large amount of spam.

Please try to post your questions or problems on a related programming board, a suitable mailing list, a programming chat-room,
or use a QA website like stackoverflow because I'm usually too busy to answer any mails related
to my code snippets. Therefore please just mail me if you found a serious bug... Thank you!


Older comments:

harry March 16, 2011 at 13:54
@all: use of 'DIRECTORY_SEPARATOR' is wrong, on a url. jonas has the right snippet.
Larry June 26, 2009 at 13:47
I'm not sure if this is a proper way to do this, but prehaps
realpath($path) . DIRECTORY_SEPARATOR
test May 11, 2009 at 14:18
[code]function add_ending_slash($path) {
return rtrim($path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
}[/code]
thankful_guy January 22, 2009 at 15:37
Thanks.
Keith February 07, 2008 at 06:17
Oops, no need to cast strlen as an int:

function add_ending_slash( $path )
{
if ( substr( $path, ( 0 - strlen( DIRECTORY_SEPARATOR ) ) ) !== DIRECTORY_SEPARATOR )
{
$path .= DIRECTORY_SEPARATOR;
}
return $path;
}
Keith February 07, 2008 at 06:16
function add_ending_slash( $path )
{
if ( substr( $path, ( 0 - ( int ) strlen( DIRECTORY_SEPARATOR ) ) ) !== DIRECTORY_SEPARATOR )
{
$path .= DIRECTORY_SEPARATOR;
}
return $path;
}