我想获得最后的路径段的URL:如何获取URL中的最后一个路径?
http://blabla/bla/wce/news.php
或http://blabla/blablabla/dut2a/news.php
例如,在这两个网址,我想要得到的路径段:“WCE '和'dut2a'。
我试过使用$_SERVER['REQUEST_URI']
,但是我得到了整个URL路径。
我想获得最后的路径段的URL:如何获取URL中的最后一个路径?
http://blabla/bla/wce/news.php
或http://blabla/blablabla/dut2a/news.php
例如,在这两个网址,我想要得到的路径段:“WCE '和'dut2a'。
我试过使用$_SERVER['REQUEST_URI']
,但是我得到了整个URL路径。
尝试:
$url = 'http://blabla/blablabla/dut2a/news.php';
$tokens = explode('/', $url);
echo $tokens[sizeof($tokens)-2];
假设$tokens
具有至少2个元素。
使用explode功能
$arr = explode("/", $uri);
试试这个:
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']);
我也从评论的几个URL进行了测试。我将不得不假设所有路径都以斜线结尾,因为我无法确定/ bob是目录还是文件。这将假定它是一个文件,除非它也有一个斜线。
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
试试这个:
$parts = explode('/', 'your_url_here');
$last = end($parts);
如果URL具有尾部斜线 – insign 2013-11-11 22:24:45
很容易
<?php
echo basename(dirname($url));
?>
另一种解决方案:
$last_slash = strrpos('/', $url);
$last = substr($url, $last_slash);
1:获得最后的斜线位置 2:获得子在拉斯维加斯之间牛逼斜线和字符串的结尾
看吧:TEST
如果你想处理一个绝对URL,那么你可以使用parse_url()
(它不与相对URL)。
$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;
完整的代码示例在这里:http://codepad.org/klqk5o29
我自己写的一个小功能,以获得一个网址的最后一个目录/文件夹。它只适用于真实/现有的网址,而不是理论网址。在我的情况下,情况总是如此,所以...
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
}
适合我!请享用!并赞扬以前的答案!
bahamut100,如果这是正确的答案,那么您应该通过点击旁边的白色复选标记来接受它。 – 2010-02-16 13:56:56
@ bahamut100,不客气。尽管我会去接受亚历克斯的回答。 – 2010-02-16 13:59:53
@Bart K.没关系,你的工作也会完成! +1 – alex 2010-02-16 14:05:48