题
我想像得到的最后一段路径在一个网址:
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的元素。
其他提示
试试这个:
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']);
我还检测了它的几个网址的意见。我必须要假设所有的路径终端用斜线,因为我不能确定如果/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
这是很容易
<?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
将返回的尾随后名称的组成部分的路径dirname
将返回的父目的的路径
试试这个:
$parts = explode('/', 'your_url_here');
$last = end($parts);
另一种解决方案:
$last_slash = strrpos('/', $url);
$last = substr($url, $last_slash);
1:得到的最后一个斜杠的位置 2:越来越substring之间的最后削减和结束的字符串
看看这里: 测试
如果你要处理一个绝对的网址,然后你可以用 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
使用 爆炸 功能
$arr = explode("/", $uri);
我写我自己一个小的功能得到的最后一个dir/文件夹中的一个网址。它仅适用于真正的/现有的网址,不是理论上的。在我的情况下,这一直是这种情况,所以...
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
}
为我工作!享受!和荣誉的以前的答案!!!
不隶属于 StackOverflow