PHP Get only part of the full path

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

I get the full path to the current folder:

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

I want to select only "/ public_html / test2"

How can i do this? Thank!

+3
source share
7 answers

I think you should check the methods associated with the paths:

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

You can find a solution with one of them.

+3
source

Depends on how fixed the format is. In the lightest 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;
+1
source
<?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'
?>
+1

, , , str_replace:

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

/home/USER :

$path=str_replace("/home/USER", "", getcwd());
0
    $dbc_root = getcwd(); // That will return let 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 ;-)

$dbc_root /home/USER

, var ... :

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

Hope this helps you in the right direction.

0
source

Try this "/ home / pophub / public_html /" - this is the text that you remove from getcwd ()

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

Source: https://habr.com/ru/post/1736546/


All Articles