1

String # 1:

/string/morestring/thename

String # 2:

/string/morestring/thename/

Regex:

[^\/]*[\/]*$

The above regex matches both last segments...

How can the regex match only the last word on both "thename" AND "thename/", with or without final slash?

hakre
  • 184,866
  • 48
  • 414
  • 792
Codex73
  • 5,611
  • 9
  • 55
  • 75

4 Answers4

9

I would just use basename().

jeroen
  • 90,003
  • 21
  • 112
  • 129
  • +1. Would basename work for a URI if PHP is running on Windows though? (since the path separator is \\) – Ben Feb 08 '11 at 01:50
  • 1
    @Ben According to the manual: `On Windows, both slash (/) and backslash (\\) are used as directory separator character.` – jeroen Feb 08 '11 at 01:54
  • @jeroen. What about the extension? basename('/test/file.gif') is 'file', not 'file.gif' (AFAIK) – Ben Feb 08 '11 at 01:57
  • @Ben No, the extension is included. Perhaps you are looking at the example in the manual where they used the second parameter? – jeroen Feb 08 '11 at 02:04
4
[^\/]+\/?$

http://rubular.com/r/TeAEWM0jsd

deceze
  • 491,798
  • 79
  • 706
  • 853
  • Selecting solution since question was regarding regex and not implicitly attached to a particular language or method. All answers solve different problems, very well appreciated. – Codex73 Feb 08 '11 at 03:10
3

jeroen's basename solution is very good but might not work on windows, it would also cut out the extension if the URI ends with .something too.

I'd do this:

 $last = array_pop(explode('/',rtrim($s,'/')));
Ben
  • 19,879
  • 11
  • 69
  • 113
1

Another option:

$last = array_pop(preg_split('#/+#', rtrim($s, '/')));
shadowhand
  • 3,204
  • 18
  • 23