0

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]);
user3761459
  • 519
  • 2
  • 5
  • 10
  • There are a few different approaches for this. Here are a [few suggestions](http://stackoverflow.com/questions/5921075/get-last-word-from-url-after-a-slash-in-php) to a similar question. Hope it helps. – bcintegrity Jun 20 '14 at 21:57

4 Answers4

0

after you explode the array use the end() function. That will always grab the last element in the array.

http://us1.php.net//manual/en/function.end.php

AndrewTet
  • 1,172
  • 8
  • 20
0

I'm sure there are other methods, I would use array_pop

$parts = explode('/', $current_url);
var_dump(array_pop($parts));

http://php.net/manual/en/function.array-pop.php "array_pop() pops and returns the last value of the array, shortening the array by one element."

but the last note is important as it affects the contents of $parts array

aland
  • 1,824
  • 2
  • 26
  • 43
0
$parts = explode("/", $url);
echo end($parts);
RohitJ
  • 543
  • 4
  • 8
0

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

Fabian Schuiki
  • 1,268
  • 7
  • 18