KRB
KRB

Reputation: 5175

What PHP function(s) should I use to cut off the end of a string?

I have a filename stored with the directory as a value.

Ex. /var/www/remove_this.php

In my PHP script I want to remove everthing after the last '/', so I can use mkdir on this path without creating a directory from the filename also.

There are so many string editing functions, I don't know a good approach. Thanks!

Upvotes: 1

Views: 161

Answers (4)

DaveyBoy
DaveyBoy

Reputation: 2915

<?php
$file="/var/www/remove_this.php";
$folder=dirname($var);
if (!file_exsts($folder))
{
  if (mkdir($folder,777,true))
  {
    echo "Folder created\n";
  } else
  {
    echo "Folder creation failed\n";
  }
} else
{
  echo "Folder exists already\n";
}
?>

Upvotes: 2

Rijk
Rijk

Reputation: 11301

You could use string functions, but for this case PHP has some smarter directory functions:

$dir = dirname('/var/www/remove_this.php'); // /var/www

pathinfo is an excellent one as well.

Upvotes: 2

gen_Eric
gen_Eric

Reputation: 227180

Use pathinfo() to get info about the file itself.

$file = '/var/www/remove_this.php';
$pathinfo = pathinfo($file);
$dir = $pathinfo['dirname']; // '/var/www/'

Upvotes: 2

Maxim Krizhanovsky
Maxim Krizhanovsky

Reputation: 26699

dirname() will return you the directory part of the path

Upvotes: 7

Related Questions