doujiao1984 2019-05-23 15:12
浏览 210
已采纳

在PHP中获取URL的一部分并不完全正常

I've this code here:

$url = 'https://www.my-page.de/account/show/4913';

echo substr( $url, strrpos( $url, '/' ) + 1 );

This returns me the needed id:

4913

Now the problem begins. In some cases the URL looks like this:

$url = 'https://www.my-page.de/account/show/4913/';

$url = 'https://www.my-page.de/account/show/4913/?conversationId=xxx';

This means that my code don't works anymore. So is there any way to be 100 % sure that I always get my ID from the URL? The ID is always at the same position from the beginning on but the end can be different.

Update

When I've this code here I'm getting not the last part anymore. Any idea why and how to fix this?:

$url = 'https://my-page.de/account/show/4913/';
$id = basename( dirname( $url ) );

I just want to be sure that it works in every situation. In this case the selected part is:

show
  • 写回答

2条回答 默认 最新

  • douxun7992 2019-05-23 15:17
    关注

    You could use functions that are meant for directories and/or URLs:

    echo basename(dirname($url));
    //or 
    echo basename(pathinfo($url, PATHINFO_DIRNAME));
    //or
    echo basename(parse_url($url, PHP_URL_PATH));
    

    The last one may return the filename if you had https://www.my-page.de/account/show/4913/index.php so you would want to use:

    echo basename(dirname(parse_url($url, PHP_URL_PATH)));
    

    Lot's of possibilities depending on what you need. The point is that there are specific functions for working with directories, filenames and URLs so that you don't have to treat them as just strings that have no meaning but unlimited possibilities..

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失