PHP:只回显url的最后一部分,intead代码打印整个url

PHP:只回显url的最后一部分,intead代码打印整个url,php,Php,我想打印url中“/”之后的最后几个字符。但是它打印的是整个url,我希望输出的是“index.php”,而不是打印整个url 我该怎么做才对呢 $data = $_SERVER['REQUEST_URI']; $whatIWant = substr($data, strpos($data, "/") + 1); echo $whatIWant; 您可以看到它您应该通过 <?php $actual_link = "http://$_SERVER[HTTP_HOST]

我想打印url中“/”之后的最后几个字符。但是它打印的是整个url,我希望输出的是“index.php”,而不是打印整个url

我该怎么做才对呢

 $data = $_SERVER['REQUEST_URI'];
    $whatIWant = substr($data, strpos($data, "/") + 1); 
     echo $whatIWant;

您可以看到它

您应该通过

<?php
$actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$getpath=explode("/",$actual_link);
echo end($getpath);
?>
第2步:用斜杠分解

explode("/",$actual_link)
第3步:获取最后一部分

end($getpath);
试试这个

<?php
$data = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$whatIWant = explode("/",$data);
 echo end($whatIWant);?>

您也可以使用
strrchr
以这种方式进行尝试:

$url = 'http://spiritofethiopia.com/test/test/test/index.php';
$str = substr(strrchr($url, '/'), 1);
echo $str;
strrchr
-查找字符串中最后出现的字符

试试这个:

工作方案

<?php 

  $url = 'http://test/test/test/index.php';
  $tokens = explode('/', $url);
  echo $tokens[sizeof($tokens)-1];

?>

您可以使用preg\u match和正确的RegExp来捕获URL的结尾

<?php
$data = $_SERVER['REQUEST_URI'];

if(preg_match('#/([^/]*?)$#', $data, $matches) == 1) {
    echo $matches[1];
}
else {
    // Should not happen
    /*
     * Throw exception
     */
}

尝试strripos而不是strpos,它可能会起作用

<?php
    $data = $_SERVER['REQUEST_URI'];
    $whatIWant = substr($data, strripos($data, "/") + 1); 
        echo $whatIWant;
    ?>


当PHP为您提供内置函数时,使用explode来破解文件名:
echo pathinfo(parse\u url($\u SERVER['REQUEST\u URI',PHP\u url\u PATH),pathinfo\u BASENAME)这个问题有什么不同:?似乎很相似?strrpos更好。请尝试strrpos。这是最好的解决方案。请参阅我给出的代码。如果字符串包含更多斜杠,则说明您的代码根本不起作用。@anantkumarsingh我已更正了错误answer@JenisPatel:它工作正常,我也检查了你的url。我认为它不适合你,因为你正在使用
substr($test,15)
您给出的是一个固定的位置号
15
因此对于
$test='test/test/test/index.php';
输出将是
/test/index.php
而不是
index.php
好的:)只需检查更新的答案即可,但是我不想手动将url放置到我的所有页面。您也可以使用
$\u服务器['REQUEST\u URI']
而不是手动url。我只是使用手动url为您提供了一个示例。效果非常好。谢谢大家!@Jocker这很有帮助意味着接受我的答案不!这并不意味着OP必须完全接受你的答案。也许是upV,因为工具提示上说:这个答案很有用;有一篇关于元如何接受的好帖子,这可能有助于OP决定他可以/应该选择/接受哪个答案:完美地工作,有一个很好的解释!谢谢,很高兴帮助您:)
<?php
    $data = $_SERVER['REQUEST_URI'];
    $whatIWant = substr($data, strripos($data, "/") + 1); 
        echo $whatIWant;
    ?>