Codex73
Codex73

Reputation: 5766

Extracting the last segment on an URI

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?

Upvotes: 1

Views: 1311

Answers (4)

shadowhand
shadowhand

Reputation: 3201

Another option:

$last = array_pop(preg_split('#/+#', rtrim($s, '/')));

Upvotes: 1

Ben
Ben

Reputation: 21249

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,'/')));

Upvotes: 3

deceze
deceze

Reputation: 522076

[^\/]+\/?$

http://rubular.com/r/TeAEWM0jsd

Upvotes: 4

jeroen
jeroen

Reputation: 91734

I would just use basename().

Upvotes: 9

Related Questions