user1555076
user1555076

Reputation: 327

Edit filepath PHP

I have a delete button on my page, that delete button has to delete a certain entry in my database (not too difficult), it has to delete the entire folder where the file that holds the delete button is in (also doable), but I also want it to delete another folder that's placed somewhere else and I'm not sure how to do that. Using

dirname(__FILE__);

I am able to get the filepath where the file holding the delete button is located. That results in this:

mywebsite.nl/subdomains/dongen/httpdocs/s-gravenmoer/aandrijvingenenbesturingen/logo4life

The filepath that I also want to delete is quite similair, but a little different. The last 3 folders a variable, so their lenght (in characters) is always different. However, the second to last folder has to be deleted from this filepath so this remains:

 mywebsite.nl/subdomains/dongen/httpdocs/s-gravenmoer/logo4life

Is there a way to do this with PHP? Using substr or something like that perhaps?

Thanks!

Upvotes: 0

Views: 119

Answers (4)

Prasanth
Prasanth

Reputation: 5258

$path = "mywebsite.nl/subdomains/dongen/httpdocs/s-gravenmoer/aandrijvingenenbesturingen/logo4life";
$regex = "/(.*\/).*\/(.*)/";
$matches = array();
preg_match($regex,  $path, $matches);
// var_dump($matches);
$new_path = $matches[1].$matches[2];
echo $new_path;

Above code uses preg_match for matching a regexp in a string.

Upvotes: 0

vascowhite
vascowhite

Reputation: 18440

You don't need anything fancy, as you guessed, a simple str_replace will do it:-

$file = 'mywebsite.nl/subdomains/dongen/httpdocs/s-gravenmoer/aandrijvingenenbesturingen/logo4life';
var_dump(str_replace('aandrijvingenenbesturingen/', '', $file));

Output:-

string 'mywebsite.nl/subdomains/dongen/httpdocs/s-gravenmoer/logo4life' (length=62)

Upvotes: 0

rationalboss
rationalboss

Reputation: 5389

You can try using "glob." Details in www.php.net/glob

You can try:

$files = glob('subdomains/dongen/httpdocs/*/logo4life');
foreach ($files as $file) {
    unlink($file); // note that this is very dangerous though, you may end up deleting a lot of files
}

Upvotes: 1

Krycke
Krycke

Reputation: 3186

I think this should do the trick:

$folderToRemove = preg_replace( '#^(.*)/(.*?)/(.*?)$#', "$1/$3", dirname(__FILE__) );

Upvotes: 2

Related Questions