Adrian
Adrian

Reputation: 51

PHP Get only a part of the full path

I would like to know how can I subtract only a part of the full path:

I get the full path of the current folder:

$dbc_root = getcwd(); // That will return let's say "/home/USER/public_html/test2"

I want to select only "/public_html/test2"

How can I do it? Thanks!

Upvotes: 5

Views: 2065

Answers (7)

aidangig
aidangig

Reputation: 189

Try this "/home/pophub/public_html/" is the text you are removing from the getcwd()

$dir = getcwd();
$dir1 = str_replace('/home/pophub/public_html/', '/', $dir);
echo $dir1;

Upvotes: 0

jagb
jagb

Reputation: 922

    $dbc_root = getcwd(); // That will return let's say "/home/USER/public_html/test2"
    $dbc_root .= str_replace('/home/USER', '', $dbc_root); // Remember to replace USER with the correct username in your file ;-)

After this your $dbc_root should be without /home/USER

I didn't test, if you prefer to create a new var for this... You could try:

   $slim_dbc_root = str_replace('/home/USER', '', $dbc_root);

I hope this will help you into the right direction

Upvotes: 0

Matthew
Matthew

Reputation: 48284

<?php
function pieces($p, $offset, $length = null)
{
  if ($offset >= 0) $offset++; // to adjust for the leading /
  return implode('/', array_slice(explode('/', $p), $offset, $length));
}

echo pieces('/a/b/c/d', 0, 1); // 'a'
echo pieces('/a/b/c/d', 0, 2); // 'a/b'
echo pieces('/a/b/c/d', -2); // 'c/d'
echo pieces('/a/b/c/d', -2, 1); // 'c'
?>

Upvotes: 1

Jonathan Czitkovics
Jonathan Czitkovics

Reputation: 1614

You can replace the /home/USER with an empty string:

$path=str_replace("/home/USER", "", getcwd());

Upvotes: 0

Tatu Ulmanen
Tatu Ulmanen

Reputation: 124758

Depends on how fixed the format is. In easiest form:

$dbc_root = str_replace('/home/USER', '', getcwd());

If you need to get everything after public_html:

preg_match('/public_html.*$/', getcwd(), $match);
$dbc_root = $match;

Upvotes: 1

Andreas
Andreas

Reputation: 5335

I think you should check the path related methods:

pathinfo() - Returns information about a file path
dirname() - Returns directory name component of path
basename() - Returns filename component of path

You should be able to find a solution with one of these.

Upvotes: 7

Erik
Erik

Reputation: 20712

Well, if you know what the part of the path you want to discard is, you could simply do a str_replace:

$dbc_root = str_replace('/home/USER/', '', $dbc_root);

Upvotes: 1

Related Questions