开发者

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!


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.


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);


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;


<?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'
?>


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

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


    $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


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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜