在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:

因此,链接是动态生成的,如下所示:

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');

Regex demo: https://regex101.com/r/bE3bO5/1

输出:

约翰,史密斯

更新:

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]");