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...

Snippet information

Author:
Jonas John

License:
Public Domain

Language:
PHP

Created:
05/05/2006

Updated:
05/05/2006

Tags:


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;
}


Found a bug? Or do you have a better solution for this?
Feel free to leave a message:

Add a comment


Leave a comment

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;
}