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