我想获取URL中的最后一个路径段:
http://blabla/bla/wce/news.php 要么http://blabla/blablabla/dut2a/news.php例如,在这两个URL中,我想获得路径段:'wce'和'dut2a'.
我尝试使用$_SERVER['REQUEST_URI'],但我得到了整个URL路径.
Bar*_*ers 51
尝试:
$url = 'http://blabla/blablabla/dut2a/news.php';
$tokens = explode('/', $url);
echo $tokens[sizeof($tokens)-2];
Run Code Online (Sandbox Code Playgroud)
假设$tokens至少有2个元素.
ale*_*lex 27
试试这个:
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']);
Run Code Online (Sandbox Code Playgroud)
我还用评论中的几个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
Run Code Online (Sandbox Code Playgroud)
Ste*_*rov 22
这很容易
<?php
echo basename(dirname($url)); // if your url/path includes a file
echo basename($url); // if your url/path does not include a file
?>
Run Code Online (Sandbox Code Playgroud)
basename 将返回路径的尾随尾随名称组件dirname 将返回父目录的路径http://php.net/manual/en/function.dirname.php
http://php.net/manual/en/function.basename.php
试试这个:
$parts = explode('/', 'your_url_here');
$last = end($parts);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
78107 次 |
| 最近记录: |