1

I have a URL that is in the following structure: http://somewebsite.com/directory1/directory2/directory3...

I'm trying to get the last directory name from this url, but the depth of the url isn't always constant so i don't think i can use a simple substr or preg_match call - is there a function to get the last instance of a regular expression match from a string?

2
  • 1
    It looks like basename would be sufficient here? If not, what is the regex in question? Commented Dec 16, 2011 at 14:23
  • 1
    preg_match('/\/([^/])$/' ... ? Commented Dec 16, 2011 at 14:23

2 Answers 2

4

Just use:

basename( $url )

It should have the desired effect

Sign up to request clarification or add additional context in comments.

Comments

1

Torben's answer is the correct way to handle this specific case. But for posterity, here is how you get the last instance of a regular expression match:

preg_match_all('/pattern/', 'subject', $matches, PREG_SET_ORDER);
$last_match = end($matches); // or array_pop(), but it modifies the array

$last_match[0] contains the complete match, $last_match[1] contains the first parenthesized subpattern, etc.

Another point of interest: your regular expression '/\/([^/])$/' should work as-is because the $ anchors it to the end.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.