douhuan1901 2014-06-20 21:53
浏览 173
已采纳

从URL获取最后一个参数

I want to get the last parameter from the following type of structure:

$current_url = "/wp/author/admin/1";    

So, from above url I will like to get "1"

The following code will return it correctly, but here I'm specifying the exact position of the variable. How can I get the last parameter without specifying its position (eg. no matter how many parameters are in the URL, just get the last one):

$parts = explode('/', $current_url);
var_dump($parts[4]);
  • 写回答

4条回答 默认 最新

  • duancan65665 2014-06-20 22:56
    关注

    I would suggest using a regular expression for this, as you can do quite a few nice things, e.g. also allow URLs that end in /:

    if (!preg_match('/\/([^\/]*)\/?$/', $current_url, $matches)
        // do something if the URL does not match the pattern
    $lastComponent = $matches[1];
    

    What's happening here? The regular expression matches if it can find a forward slash (the \/) followed by any number of characters that are not slashes (the ([^\/]*)), which may then optionally be followed by another slash (the \/?), and then arrives at the end of the string (the $).

    The function returns a value that evaluates to false if the regular expression did not match, so you are prepared for garbage input and may emit a warning if appropriate. Notice the parentheses in ([^\/]*), which will take all the characters mathced here (everything from the slash to the end of the input string or the last slash), and put it into its own match ($matches[1]).

    I recommend you try regexpal.com if you want to debug and check your regular expressions. They are very powerful tools and quite underused in programming. Especially in PHP, where you get nice functions for them (e.g. preg_match, preg_match_all, and preg_match_split).

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

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器