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');
?>
Related
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
http://localhost/mc/site-01-up/index.php?c=lorem-ipsum
$address = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$stack = explode('/', $_SERVER["REQUEST_URI"]);
$file = array_pop($stack);
echo $file;
result - index.php?c=lorem-ipsum
How to get just file name (index.php) without $_GET variable, using array_pop if possible?
Another method that can get the filename is by using parse_url — Parses a URL and return its components
<?php
$url = "http://localhost/mc/site-01-up/index.php?c=lorem-ipsum";
$data = parse_url($url);
$array = explode("/",$data['path']);
$filename = $array[count($array)-1];
var_dump($filename);
Result
index.php
EDIT:
Sorry for posting this answer as it is almost identical to the selected one. I didnt see the answer so posted. But I cannot delete this as it is seen as a bad practice by moderators.
I will follow parse_url() like below (easy to understand):-
<?php
$url = 'http://localhost/mc/site-01-up/index.php?c=lorem-ipsum';
$url= parse_url($url);
print_r($url); // to check what parse_url() will outputs
$url_path = explode('/',$url['path']); // explode the path part
$file_name = $url_path[count($url_path)-1]; // get last index value which is your desired result
echo $file_name;
?>
Output:- https://eval.in/606839
Note:- tested with your given URL. Check for other type of URL's at your end. thanks.
Try this, not tested:
$file = $_SERVER["SCRIPT_NAME"];
$parts = Explode('/', $file);
$file = $parts[count($parts) - 1];
echo $file;
One way of doing it would be to simply get the basename() of the file and then strip-out all the Query Part using regex or better still simply do pass the $_SERVER['PHP_SELF'] result to the basename() Function. Both will yield the same result though the 2nd approach seems a little more intuitive.
<?php
$fileName = preg_replace("#\?.*$#", "", basename("http://localhost/mc/site-01-up/index.php?c=lorem-ipsum"));
echo $fileName; // DISPLAYS: index.php
// OR SHORTER AND SIMPLER:
$fileName = basename($_SERVER['PHP_SELF']);
echo $fileName; // DISPLAYS: index.php
If you are trying to use the GET method without variable name, another option would be using the $_SERVER["QUERY_STRING"]
http://something.com/index.php?=somestring
$_SERVER["QUERY_STRING"] would return "somestring"
I have multiple files in a directory for pages.
All the pages are the same except the content I enter based on
rental inspections.
bedroom1.php
bedroom2.php
bedroom3.php
But to get them to use the right header I need them to see the
correct header based on their own filename.
bedroom1.php to include header1.php
bedroom2.php to include header2.php
bedroom3.php to include header3.php
.......
bedroom10.php to include header10.php
I can get the filename easy enough.
I'm trying to use preg_match(Maybe should use something else?)
but with not getting any errors in the logs so I'm not sure
what I'm missing and not knowing enough about file comparing
I'm lost.
EDIT: ADDED : Forgot to add, this code is in bedroom1.php etc...
Thanks in advance
<?php
$file = $_SERVER["SCRIPT_NAME"];
$break = Explode('/', $file);
$pfile = $break[count($break) - 1];
if (preg_match('/bedroom . $i .php/', $pfile, $i)) {
$number = $i[1];
foreach(array('header') as $base) {
include_once "$base$number.php";
}
}
?>
It should be:
if (preg_match('/bedroom(\d+)\.php/', $pfile, $i)) {
You need to use \d+ to match numeric digits, and put it inside parentheses to make it a capture group, so you can access it with $i[1].
Try this one:
$file = basename($_SERVER['SCRIPT_NAME'], '.php');
$base = 'header';
$parts = array();
if (preg_match('/bedroom(\d+)/', $file, $parts)) {
include_once $base . $parts[1] . '.php';
} else {
// the file doesn't follow the bedroom{number}.php structure
}
Good luck!
use this
basename($_SERVER['SCRIPT_NAME'])
you get the script name
$file = $_SERVER["SCRIPT_NAME"];
$baseName=basename($file);
$base="header";
preg_match_all('/\d+/', $baseName, $baseNameInt);
$basNameFile=$baseNameInt[0][0];
if(file_exists("$base$basNameFile.php")){
include_once("$base$basNameFile.php");
} else {
// ...
}
Not sure what your array contains that necessitates the foreach (if that is just example code) but why not just:
$array = array('header');
$suffix = str_replace($array, '', basename(__FILE__));
foreach($array as $base) {
if(file_exist("$base$suffix")) {
include_once("$base$suffix");
}
}
If the only thing that will be in the array is header then forgo the loop altogether.
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
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)