Splitting a file path in PHP

During the week, I was faced with the problem of dividing a given string containing a file path into the file name, extension and the path to the file’s directory. For example, “/home/myuser/myfile.ext”, has to be split into “/home/myuser/”, “myfile” and “ext”.

My first instinct was to use PHP’s explode(function to split the string on the forward slash. This would give me my file name and extension in the last element of the returned array and each of the directories of my path in the preceding elements. Of course, I would then have to build my directory path from these elements before returning the result, re-inserting the forward slash along the way.

This did not strike me as an elegant way to proceed. So on further reflection, I started my solution using basename(). This returns the file name and extension for a given file path. From here, I used explode to split the base file name into it’s file name and extension. Note that I did not store the “.” between the file name and extension as the specification did not require this.

Now, I needed the directory path to the file. Of course, my input string already had this information. I just had to remove the file name and extension from the end. So, I used substr() to get the sub string from the start of the source path less the length of the base file name (with it’s extension).

This struck me as being a more succinct resolution which is more intuitive to understand. I have included some sample code below.

class PathSplitter {

    function __construct() {
        $source = "/home/myuser/myfile.ext";
        echo "Source path: {$source}\n\n";

        $splitPath = $this->splitPath($source);

        echo "Split Path:\n";

    private function splitPath($source) {

        // Get the file name and extension, i.e. the basename
        $baseName = basename($source);

        // Break down the basename into file name and extension
        $parts = explode(".", $baseName);

        $name = $parts[0];
        $extension = $parts[1];

        // The path is the full path name less the basename
        $path = substr($source, 0, -strlen($baseName));

        $splitPath = array(
            "path" => $path,
            "name" => $name,
            "extension" => $extension
        return $splitPath;


I work as an Developer/Operations Engineer and this is a technical blog sharing my knowledge.

Tagged with: , ,
Posted in PHP

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: