URL - 在 PHP 中获取最后一部分
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19541080/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
URL - Get last part in PHP
提问by Paulo César
I have my url:
我有我的网址:
http://domain/fotografo/admin/gallery_bg.php
and i want last part of the url:
我想要网址的最后一部分:
gallery_bg.php
but, I do not want to link static, ie, for each page that vistitar I want to get the last part of the url
但是,我不想链接静态,即对于每个访问的页面,我想获取 url 的最后一部分
回答by w3b
use following
使用以下
<?php
$link = $_SERVER['PHP_SELF'];
$link_array = explode('/',$link);
echo $page = end($link_array);
?>
回答by jaydeep namera
Use basename function
使用 basename 函数
echo basename("http://domain/fotografo/admin/gallery_bg.php");
回答by Deepu
$url = "http://domain/fotografo/admin/gallery_bg.php";
$keys = parse_url($url); // parse the url
$path = explode("/", $keys['path']); // splitting the path
$last = end($path); // get the value of the last element
回答by MaxEcho
If it is same page:
如果是同一页:
echo $_SERVER["REQUEST_URI"];
or
echo $_SERVER["SCRIPT_NAME"];
or
echo $_SERVER["PHP_SELF"];
In each case a back slash(/
gallery_bg.php) will appear. You can trim it as
在每种情况下,/
都会出现一个反斜杠(gallery_bg.php)。您可以将其修剪为
echo trim($_SERVER["REQUEST_URI"],"/");
or split the url by /
to make an array and get the last item from array
或拆分 url/
以创建一个数组并从数组中获取最后一项
$array = explode("/",$url);
$last_item_index = count($url) - 1;
echo $array[$last_item_index];
or
或者
echo basename($url);
回答by Arvind Kala
you can use basename($url) function as suggested above. This returns the file name from the url. You can also provide the file extension as second argument to this function like basename($url, '.jpg'), then the filename without the extension will be served.
您可以使用上面建议的 basename($url) 函数。这将从 url 返回文件名。您还可以提供文件扩展名作为此函数的第二个参数,例如 basename($url, '.jpg'),然后将提供不带扩展名的文件名。
Eg:
例如:
$url = "https://i0.com/images/test.jpg"
then echo basename($url) will print test.jpg
and echo basename($url,".jpg") will print test
回答by Anand Solanki
Try this:
尝试这个:
Here you have 2 options.
1. Using explode function.
$filename = end(explode('/', 'http://domain/fotografo/admin/gallery_bg.php'));
2. Use basename function.
$filename = basename("http://domain/fotografo/admin/gallery_bg.php");
- Thanks
- 谢谢
回答by iniravpatel
$basepath = implode('/', array_slice(explode('/', $_SERVER['SCRIPT_NAME']), 0, -1)) . '/';
$uri = substr($_SERVER['REQUEST_URI'], strlen($basepath));
if (strstr($uri, '?')) $uri = substr($uri, 0, strpos($uri, '?'));
$url = trim($uri, '/');
In PHP 7 the accepted solution is giving me the error that only variables are allowed in explode so this works for me.
在 PHP 7 中,接受的解决方案给了我一个错误,即仅允许变量爆炸,所以这对我有用。
回答by Nil'z
$url = $_SERVER["PHP_SELF"];
$path = explode("/", $url);
$last = end($path);