在php中输出URL的一部分

Output a part of URL in php

因此,我动态生成了遵循以下格式的页面:

 http://example.com/name/first_name/last_name/John%2C+Smith

输出url最后一部分的php代码是什么?

所以,它变成了 "John, Smith"。

非常感谢。

编辑:

我意识到 URL 以另一个 / 结尾,下面给出的答案没有找到它。我应该做出什么改变?

http://example.com/name/first_name/last_name/John%2C+Smith/

编辑 2:

所以,link动态生成如下:

href="http://example.com/name/first_name/last_name/<?php echo $full_name ?>"

拆分 url,获取最后一个片段,然后 URL 对其进行解码:

<?
$urlarray=explode("/",$url);
$end=$urlarray[count($urlarray)-1];
$end=urldecode($end);
//go on using $end then
?>

你可以用正则表达式来做到这一点。

echo preg_replace_callback('~.*/(.*)~', 
     function($matches) { 
          return urldecode($matches[1]);
     },
     'http://example.com/name/first_name/last_name/John%2C+Smith');

正则表达式演示:https://regex101.com/r/bE3bO5/1

输出:

John, Smith

更新:

echo preg_replace_callback('~.*/(.+)~', 
function($matches) { 
     return rtrim(urldecode($matches[1]), '/');
},
'http://example.com/name/first_name/last_name/John%2C+Smith/');

您可以将 parse_url 与第二个参数一起使用 PHP_URL_PATH

$url = urldecode("http://example.com/name/first_name/last_name/John%2C+Smith");
$arr = array_filter(explode('/',parse_url($url, PHP_URL_PATH)));
print_r(end($arr));

已编辑:

根据动态 url 的要求,您可以使用

$url = urldecode("http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]");