我正在尝试获取此url字符串的最后一部分:national/italy/serie-a/20152016/s11663/
我的目标是得到:s11663这是我的代码:

$path = parse_url("national/italy/serie-a/20152016/s11663/", PHP_URL_PATH);
$pathFragments = explode('/', $path);
$end = end($pathFragments);
var_dump($end);

但我得到:
字符串(0)“”
我做错了什么?

最佳答案

因为最后有一个尾随的/,所以必须得到最后的第二个:

$path = parse_url("national/italy/serie-a/20152016/s11663/", PHP_URL_PATH);
$pathFragments = explode('/', $path);
array_pop($pathFragments); // remove last (empty value)
$end = end($pathFragments);
var_dump($end);

查看$pathFragments对您的问题的输出:
Array
(
    [0] => national
    [1] => italy
    [2] => serie-a
    [3] => 20152016
    [4] => s11663
    [5] =>
)

此代码适用于以/结尾和不以../s11663/结尾的字符串:
$path = parse_url("national/italy/serie-a/20152016/s11663", PHP_URL_PATH);
$pathFragmenst = (substr($path, -1) == '/') ?
    $pathFragments = explode('/', $path, -1) :
    $pathFragments = explode('/', $path);

$end = end($pathFragments);
var_dump($end);

../s11663的输出:https://3v4l.org/BWjkd
字符串(6)“s11663”
url_parse的输出:https://3v4l.org/H7fP9
字符串(6)“s11663”
笔记:
1-此代码:
$pathFragmenst = (substr($path, -1) == '/') ?
    $pathFragments = explode('/', $path, -1) :
    $pathFragments = explode('/', $path);

是这个的缩写:
if(substr($path, -1) == '/'){
    $pathFragments = explode('/', $path, -1);
}else{
    $pathFragments = explode('/', $path);
}

2-我不知道这个字符串是不是parse_url的结果,或者你真的在试图解析它,但是
var_dump(parse_url("national/italy/serie-a/20152016/s11663", PHP_URL_PATH));

意志输出
字符串(38)“National/Italy/Serie-A/20152016/S11663”
,因此不需要它-除非您尝试分析如下内容:
http://example.com/national/italy/serie-a/20152016/s11663/
^^^^^^^^^^^^^^^^^^^
我把它留在原处,以防你要使用完整的网址…

关于php - 无法获取网址的最后一部分,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35959084/

10-08 21:34