我想獲得最後的路徑段的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