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

报告相同问题?

悬赏问题

  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用