Tuesday, 23 January 2018

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

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/'



check for other options:
1) realpath($path) . DIRECTORY_SEPARATOR
2) function add_ending_slash($path) {
return rtrim($path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
}
3) function add_ending_slash( $path )
{
if ( substr( $path, ( 0 - strlen( DIRECTORY_SEPARATOR ) ) ) !== DIRECTORY_SEPARATOR )
{
$path .= DIRECTORY_SEPARATOR;
}
return $path;
}
4) function add_ending_slash( $path )
{
if ( substr( $path, ( 0 - ( int ) strlen( DIRECTORY_SEPARATOR ) ) ) !== DIRECTORY_SEPARATOR )
{
$path .= DIRECTORY_SEPARATOR;
}
return $path;
}

0 comments:

Post a Comment