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条)

报告相同问题?

悬赏问题

  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条