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
  • 193,403
  • 52
  • 435
  • 836
Codex73
  • 5,690
  • 11
  • 56
  • 76

4 Answers4

9

I would just use basename().

jeroen
  • 91,079
  • 21
  • 114
  • 132
  • +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
  • 510,633
  • 85
  • 743
  • 889
  • 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
  • 20,737
  • 12
  • 71
  • 115
1

Another option:

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