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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵