Karl Schmidt
Karl Schmidt

Reputation: 52

Trying to get rid of a part of a string (used as file path) in order to go back a directory

My problem is as follows. My PHP code relies on a string to determine a file directory, by removing the last part of the path. I want to go back a directory. Consider the following example:

Original Input:

$dir = "this/is/a/files/location"

Desired Output:

$dir = "this/is/a/files"

Basically, I need it to remove everything to the right of the first "/".

Thank you so much for your help with this!

Upvotes: 1

Views: 76

Answers (3)

Professor Abronsius
Professor Abronsius

Reputation: 33804

Another method, using str_replace and basename

    $dir = "this/is/a/files/location";
    echo str_replace( '/' . basename( $dir ), '', $dir );

output:

this/is/a/files

update [ 01.04.2019 ] Having just been given a plus one I looked again at this and have an additional snippet to offer ~ it seems to me much easier than my previous offering - chdir('../')

    /* where did we start off? */
    printf('Current directory: %s<br />', getcwd() );

    /* go up a level */
    chdir('../');

    /* where are we now? */
    printf('Current directory: %s', getcwd() );

Upvotes: 1

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72289

You have to use substr() along with strrpos()

$dir = "this/is/a/files/location";

$dir = substr($dir, 0, strrpos( $dir, '/'));

Output:- https://eval.in/949366

Upvotes: 1

Kaushik C
Kaushik C

Reputation: 114

This Might Help

$dir = "this/is/a/files/location"; 
$popped = explode('/',$dir);
array_pop($popped);
$dir = implode('/',$popped);

Upvotes: 1

Related Questions