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
Related
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"
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');
?>
I am trying to do a URL parser for my project, something very simple that gets an URL like you would enter it in a browser and convert it into a valid URL, once that is done parse such URL and grab all the images with full paths.
I was able to "fix" the user entered URL and pre-pend the http when needed, remove the last / on domain only (`http://www.domain.com/ become http://www.domain.com but http://www.domain.com/test/ stays unchanged).
The problem that I am having is dirname is parsing the path of certain folders.
my code looks something like this:
<?php
$url = 'www.domain.com/~folder/'; //This is a variable that changes often
$url = $this->fix_url($url); //$url is now http://www.domain.com/~folder/
$url_image = 'image.png';
$parse = parse_url($url);
$dir = (isset($parse['path'])?dirname($parse['path']):'');
$ret = 'http://'.$parse['host'].$dir.'/'.$url_image;
var_dump($parse, $dir, $ret);
?>
The way I was able to go around the problem is with this code that I use to find $dir
<?php
$path = (isset($parse['path'])?$parse['path']:'/');
$tmp = explode('/', $path);
if(is_array($tmp) && count($tmp) > 0){
array_pop($tmp);
}
$dir = implode('/', $tmp);
?>
But there must be a better way
How can the first URL segment be extracted from the full URL? The first URL segment should be cleaned to replace the - with a space .
Full URL
http://www.domain.com/River-Island/River-Island-T-Shirt-with-Triangle-Girl-Print/Prod/pgeproduct.aspx?iid=2516020
Desired Outpput
River Island
You can use:
$url = 'http://www.domain.com/River-Island/River-Island-T-Shirt-with-Triangle-Girl-Print/Prod/pgeproduct.aspx?iid=2516020';
$parsed = parse_url($url);
$path = $parsed['path'];
$path_parts = explode('/', $path);
$desired_output = $path_parts[1]; // 1, because the string begins with slash (/)
$page = explode('/', substr($_SERVER['REQUEST_URI'], 1), 2);
echo str_replace("-"," ", $page[0]);
Try this: /http:\/\/[^\/]+\/([^\/]+)/i
See here: http://regex101.com/r/lB9jN7
$path = parse_url($url, PHP_URL_PATH);
$first = substr($path, 0, strpos($path, '/'));
Check the docs for these three functions. Maybe you'll have to strip a slash from the beginning of the path, I'm not sure.
have you using CodeIgniter ...???then it could be
$this->uri->segment(segment number of url);
and its need to load uri library in Controller
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