PHP Get only a part of the full path - php

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;

Related

Trim function is removing my last character in different strings [duplicate]

I would like get the last path segment in a URL:
http://blabla/bla/wce/news.php or
http://blabla/blablabla/dut2a/news.php
For example, in these two URLs, I want to get the path segment: 'wce', and 'dut2a'.
I tried to use $_SERVER['REQUEST_URI'], but I get the whole URL path.
Try:
$url = 'http://blabla/blablabla/dut2a/news.php';
$tokens = explode('/', $url);
echo $tokens[sizeof($tokens)-2];
Assuming $tokens has at least 2 elements.
Try this:
function getLastPathSegment($url) {
$path = parse_url($url, PHP_URL_PATH); // to get the path from a whole URL
$pathTrimmed = trim($path, '/'); // normalise with no leading or trailing slash
$pathTokens = explode('/', $pathTrimmed); // get segments delimited by a slash
if (substr($path, -1) !== '/') {
array_pop($pathTokens);
}
return end($pathTokens); // get the last segment
}
echo getLastPathSegment($_SERVER['REQUEST_URI']);
I've also tested it with a few URLs from the comments. I'm going to have to assume that all paths end with a slash, because I can not identify if /bob is a directory or a file. This will assume it is a file unless it has a trailing slash too.
echo getLastPathSegment('http://server.com/bla/wce/news.php'); // wce
echo getLastPathSegment('http://server.com/bla/wce/'); // wce
echo getLastPathSegment('http://server.com/bla/wce'); // bla
it is easy
<?php
echo basename(dirname($url)); // if your url/path includes a file
echo basename($url); // if your url/path does not include a file
?>
basename will return the trailing trailing name component of path
dirname will return the parent directory's path
http://php.net/manual/en/function.dirname.php
http://php.net/manual/en/function.basename.php
Try this:
$parts = explode('/', 'your_url_here');
$last = end($parts);
$arr = explode("/", $uri);
Another solution:
$last_slash = strrpos('/', $url);
$last = substr($url, $last_slash);
1: getting the last slash position
2: getting the substring between the last slash and the end of string
Look here: TEST
If you want to process an absolute URL, then you can use parse_url() (it doesn't work with relative urls).
$url = 'http://aplicaciones.org/wp-content/uploads/2011/09/skypevideo-500x361.jpg?arg=value#anchor';
print_r(parse_url($url));
$url_path = parse_url($url, PHP_URL_PATH);
$parts = explode('/', $url_path);
$last = end($parts);
echo $last;
Full code example here: http://codepad.org/klqk5o29
I wrote myself a little function to get the last dir/folder of an url. It only works with real/existing urls, not theoretical ones. In my case, that was always the case, so ...
function uf_getLastDir($sUrl)
{
$sPath = parse_url($sUrl, PHP_URL_PATH); // parse URL and return only path component
$aPath = explode('/', trim($sPath, '/')); // remove surrounding "/" and return parts into array
end($aPath); // last element of array
if (is_dir($sPath)) // if path points to dir
return current($aPath); // return last element of array
if (is_file($sPath)) // if path points to file
return prev($aPath); // return second to last element of array
return false; // or return false
}
Works for me! Enjoy! And kudos to the previous answers!!!
This will keep the part after the last slash.
No worries about explode, when for example no slash is there.
$url = 'http://blabla/blablabla/dut2a/news.php';
$url = preg_replace('~.*/~', '', $url);
Will give
news.php

php get file folder name from url

I need get file folder name from url
examples:
http://domain/folder/NEEDTHIS/filename.xml
http://domain/folder/folder2/NEEDTHIS/filename.xml
http://domain/folder/folder2/folderanother/NEEDTHIS/filename.xml
I need only "NEEDTHIS" folder name only
i using this code for get file name
$parts = parse_url("http://domain/folder/NEEDTHIS/filename.xml");
$title = basename($parts['path']);
echo $title;
// Output: filename.xml
How can i get this file name folder?
With this approach you can even avoid parse_url()...:
$url = "http://domain/folder/NEEDTHIS/filename.xml";
$items = explode('/', $url);
echo $items[sizeof($items) - 2];
// Output: NEEDTHIS
Note: this solution only assumes directories/filenames are separated by a character. To be even more general, you could use DIRECTORY_SEPARATOR:
$url = "http://domain/folder/NEEDTHIS/filename.xml";
$items = explode(DIRECTORY_SEPARATOR, $url);
echo $items[sizeof($items) - 2];
Here you go. Use dirname() to get simple one-liner that works both for URL and normal dir-paths. Works too, if no file is specified in path (or when path ends at dir).
$path = 'http://example.com/root/one/two/three/four.xml';
echo end(explode('/',dirname($path)));
Outputs:
three
You can replace $path with anything.
Try this:
$url = "http://domain/folder/folder2/folderanother/NEEDTHIS/filename.xml";
$array = explode('/',$url);
$count = count($array);
echo $array[$count-2];

Subst a string reverse to the last slash

Hello. I have a string with a path. I do not need the whole path. Is it possible to substr to a last slash ? Based on the code below, I dont need the modelname.
Thanks for any hints you can give.
$path = userdir/modeldir/modelname
Try exploding the array by using the slash as a delimiter?
$pathArray = explode('/', $path);
That should give you the entire folder tree as an array.
For further information visit: http://www.php.net/explode
Bit confused,
do you want modelname? ok then use basename() See it in action
echo basename('userdir/modeldir/modelname'); //modelname
Or do you want userdir/modeldir? ok then use dirname() See it in action
echo dirname('userdir/modeldir/modelname/'); //userdir/modeldir
$path = 'userdir/modeldir/modelname';
$arr = explode('/', $path);
echo $arr[count($arr) - 1]; // Will output modelname
you can use this
$address = 'userdir/modeldir/modelname';
$a=explode("/",$address);
echo $a[2];
<?php
$path = 'userdir/modeldir/modelname';
$pathArray = explode('/', $path);
array_pop($pathArray);
$path = implode('/', $pathArray);
?>
Or, if you want it in a nice function:
<?php
function removeLast($path, $delim = '/') {
$pathArray = explode($delim, $path);
if (count($pathArray) == 1) return $pathArray[0];
array_pop($pathArray);
return implode($delim, $pathArray);
}
echo removeLast('userdir/modeldir/modelname');
?>

How to get the last path in a URL?

I would like get the last path segment in a URL:
http://blabla/bla/wce/news.php or
http://blabla/blablabla/dut2a/news.php
For example, in these two URLs, I want to get the path segment: 'wce', and 'dut2a'.
I tried to use $_SERVER['REQUEST_URI'], but I get the whole URL path.
Try:
$url = 'http://blabla/blablabla/dut2a/news.php';
$tokens = explode('/', $url);
echo $tokens[sizeof($tokens)-2];
Assuming $tokens has at least 2 elements.
Try this:
function getLastPathSegment($url) {
$path = parse_url($url, PHP_URL_PATH); // to get the path from a whole URL
$pathTrimmed = trim($path, '/'); // normalise with no leading or trailing slash
$pathTokens = explode('/', $pathTrimmed); // get segments delimited by a slash
if (substr($path, -1) !== '/') {
array_pop($pathTokens);
}
return end($pathTokens); // get the last segment
}
echo getLastPathSegment($_SERVER['REQUEST_URI']);
I've also tested it with a few URLs from the comments. I'm going to have to assume that all paths end with a slash, because I can not identify if /bob is a directory or a file. This will assume it is a file unless it has a trailing slash too.
echo getLastPathSegment('http://server.com/bla/wce/news.php'); // wce
echo getLastPathSegment('http://server.com/bla/wce/'); // wce
echo getLastPathSegment('http://server.com/bla/wce'); // bla
it is easy
<?php
echo basename(dirname($url)); // if your url/path includes a file
echo basename($url); // if your url/path does not include a file
?>
basename will return the trailing trailing name component of path
dirname will return the parent directory's path
http://php.net/manual/en/function.dirname.php
http://php.net/manual/en/function.basename.php
Try this:
$parts = explode('/', 'your_url_here');
$last = end($parts);
$arr = explode("/", $uri);
Another solution:
$last_slash = strrpos('/', $url);
$last = substr($url, $last_slash);
1: getting the last slash position
2: getting the substring between the last slash and the end of string
Look here: TEST
If you want to process an absolute URL, then you can use parse_url() (it doesn't work with relative urls).
$url = 'http://aplicaciones.org/wp-content/uploads/2011/09/skypevideo-500x361.jpg?arg=value#anchor';
print_r(parse_url($url));
$url_path = parse_url($url, PHP_URL_PATH);
$parts = explode('/', $url_path);
$last = end($parts);
echo $last;
Full code example here: http://codepad.org/klqk5o29
I wrote myself a little function to get the last dir/folder of an url. It only works with real/existing urls, not theoretical ones. In my case, that was always the case, so ...
function uf_getLastDir($sUrl)
{
$sPath = parse_url($sUrl, PHP_URL_PATH); // parse URL and return only path component
$aPath = explode('/', trim($sPath, '/')); // remove surrounding "/" and return parts into array
end($aPath); // last element of array
if (is_dir($sPath)) // if path points to dir
return current($aPath); // return last element of array
if (is_file($sPath)) // if path points to file
return prev($aPath); // return second to last element of array
return false; // or return false
}
Works for me! Enjoy! And kudos to the previous answers!!!
This will keep the part after the last slash.
No worries about explode, when for example no slash is there.
$url = 'http://blabla/blablabla/dut2a/news.php';
$url = preg_replace('~.*/~', '', $url);
Will give
news.php

Extract direct sub directory from path string

I need to extract the name of the direct sub directory from a full path string.
For example, say we have:
$str = "dir1/dir2/dir3/dir4/filename.ext";
$dir = "dir1/dir2";
Then the name of the sub-directory in the $str path relative to $dir would be "dir3". Note that $dir never has '/' at the ends.
So the function should be:
$subdir = getsubdir($str,$dir);
echo $subdir; // Outputs "dir3"
If $dir="dir1" then the output would be "dir2". If $dir="dir1/dir2/dir3/dir4" then the output would be "" (empty). If $dir="" then the output would be "dir1". Etc..
Currently this is what I have, and it works (as far as I've tested it). I'm just wondering if there's a simpler way since I find I'm using a lot of string functions. Maybe there's some magic regexp to do this in one line? (I'm not too good with regexp unfortunately).
function getsubdir($str,$dir) {
// Remove the filename
$str = dirname($str);
// Remove the $dir
if(!empty($dir)){
$str = str_replace($dir,"",$str);
}
// Remove the leading '/' if there is one
$si = stripos($str,"/");
if($si == 0){
$str = substr($str,1);
}
// Remove everything after the subdir (if there is anything)
$lastpart = strchr($str,"/");
$str = str_replace($lastpart,"",$str);
return $str;
}
As you can see, it's a little hacky in order to handle some odd cases (no '/' in input, empty input, etc). I hope all that made sense. Any help/suggestions are welcome.
Update (altered solution):
Well Alix Axel had it spot on. Here's his solution with slight tweaks so that it matches my exact requirements (eg: it must return a string, only directories should be outputted (not files))
function getsubdir($str,$dir) {
$str = dirname($str);
$temp = array_slice(array_diff(explode('/', $str), explode('/', $dir)), 0, 1);
return $temp[0];
}
Here you go:
function getSubDir($dir, $sub)
{
return array_slice(array_diff(explode('/', $dir), explode('/', $sub)), 0, 1);
}
EDIT - Foolproof implementation:
function getSubDirFoolproof($dir, $sub)
{
/*
This is the ONLY WAY we have to make SURE that the
last segment of $dir is a file and not a directory.
*/
if (is_file($dir))
{
$dir = dirname($dir);
}
// Is it necessary to convert to the fully expanded path?
$dir = realpath($dir);
$sub = realpath($sub);
// Do we need to worry about Windows?
$dir = str_replace('\\', '/', $dir);
$sub = str_replace('\\', '/', $sub);
// Here we filter leading, trailing and consecutive slashes.
$dir = array_filter(explode('/', $dir));
$sub = array_filter(explode('/', $sub));
// All done!
return array_slice(array_diff($dir, $sub), 0, 1);
}
How about splitting the whole thing into an array:
$fullpath = explode("/", "dir1/dir2/dir3/dir4/filename.ext");
$fulldir = explode("/", "dir1/dir2");
// Will result in array("dir1","dir2","dir3", "dir4", "filename.ext");
// and array("dir1", "dir2");
you should then be able to use array_diff():
$remainder = array_diff($fullpath, $fulldir);
// Should return array("dir3", "dir4", "filename.ext");
then, getting the direct child is easy:
echo $remainder[0];
I can't test this right now but it should work.
Here's a similar "short" solution, this time using string functions rather than array functions. If there is no corresponding part to be gotten from the string, getsubdir will return FALSE. The strtr segment is a quick way to escape the percents, which have special meaning to sscanf.
function getsubdir($str, $dir) {
return sscanf($str, strtr($dir, '%', '%%').'/%[^/]', $name) === 1 ? $name : FALSE;
}
And a quick test so you can see how it behaves:
$str = "dir1/dir2/dir3/dir4/filename.ext";
var_dump(
getSubDir($str, "dir1"),
getSubDir($str, "dir1/dir2/dir3"),
getSubDir($str, "cake")
);
// string(4) "dir2"
// string(4) "dir4"
// bool(false)

Categories