SirTony
12/12/2013 - 9:25 PM

Combines segments of a filesystem path into an absolute path using the system's directory separator char, and supports checking for illegal

Combines segments of a filesystem path into an absolute path using the system's directory separator char, and supports checking for illegal characters on Windows systems. The path() function also supports multi-dimensional arrays.

<?php

function path()
{
    // Determine if we are one windows, And get our path parts
    $IsWindows = strtoupper( substr( PHP_OS, 0, 3 ) ) === "WIN";
    $args = func_get_args();
    $parts = array();

    // Trim our paths to remove spaces and new lines
    foreach( $args as $part )
        $parts[] = is_array( $part ) ? trim( implode_recursive( DIRECTORY_SEPARATOR, $part ) ) : trim( $part );

    // Get our cleaned path into a variable with the correct directory seperator
    $newPath = implode( DIRECTORY_SEPARATOR, $parts );

    // Do some checking for illegal path chars
    if( $IsWindows )
    {
        $Pattern = "~[\\/:?*\"<>|\r\n]+~";
        $tempPath = preg_replace( "~^[A-Z]{1}:~", "", $newPath );
        $tempPath = trim( $tempPath, DIRECTORY_SEPARATOR );
        $tempPath = explode( DIRECTORY_SEPARATOR, $tempPath );

        foreach( $tempPath as $part )
        {
            if( preg_match( $Pattern, $part ) )
                throw new Exception( "Illegal characters in path." );
        }
    }

    return realpath( $newPath );
}

function implode_recursive( $sep, $array )
{
    $imploded = "";

    foreach( $array as $item )
    {
        if( is_array( $item ) )
            $imploded = implode_recursive( $sep, $item ) . $sep;
        else
            $imploded = $item . $sep;
    }

    return rtrim( $imploded, $sep );
}

?>