dongxingdu9594 2011-09-12 23:04
浏览 122
已采纳

获取URL PHP的最后一部分

I'm just wondering how I can extract the last part of a URL using PHP.

The example URL is:

http://domain.com/artist/song/music-videos/song-title/9393903

Now how can I extract the final part using PHP?

9393903

There is always the same number of variables in the URL, and the id is always at the end.

  • 写回答

12条回答 默认 最新

  • dongyulan6251 2011-09-12 23:08
    关注

    You can use preg_match to match the part of the URL that you want.

    In this case, since the pattern is easy, we're looking for a forward slash (\/ and we have to escape it since the forward slash denotes the beginning and end of the regular expression pattern), along with one or more digits (\d+) at the very end of the string ($). The parentheses around the \d+ are used for capturing the piece that we want: namely the end. We then assign the ending that we want ($end) to $matches[1] (not $matches[0], since that is the same as $url (ie the entire string)).

    $url='http://domain.com/artist/song/music-videos/song-title/9393903';
    
    if(preg_match("/\/(\d+)$/",$url,$matches))
    {
      $end=$matches[1];
    }
    else
    {
      //Your URL didn't match.  This may or may not be a bad thing.
    }
    

    Note: You may or may not want to add some more sophistication to this regular expression. For example, if you know that your URL strings will always start with http:// then the regex can become /^http:\/\/.*\/(\d+)$/ (where .* means zero or more characters (that aren't the newline character)).

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

报告相同问题?

悬赏问题

  • ¥15 如何提取csv文件中需要的列,将其整合为一篇完整文档,并进行jieba分词(语言-python)
  • ¥15 MapReduce结果输出到HBase,一直连接不上MySQL
  • ¥15 扩散模型sd.webui使用时报错“Nonetype”
  • ¥15 stm32流水灯+呼吸灯+外部中断按键
  • ¥15 将二维数组,按照假设的规定,如0/1/0 == "4",把对应列位置写成一个字符并打印输出该字符
  • ¥15 NX MCD仿真与博途通讯不了啥情况
  • ¥15 win11家庭中文版安装docker遇到Hyper-V启用失败解决办法整理
  • ¥15 gradio的web端页面格式不对的问题
  • ¥15 求大家看看Nonce如何配置
  • ¥15 Matlab怎么求解含参的二重积分?