1

I'm trying to get the last occurrence of an item from a materialized path. Below is a subset of possible values I've provided as an example where X, Y & Z can be any arbitrary string:

X/
X/Y/
X/Y/Z/

How can I select that last item on the path using php regex which would output the following for the corresponding lines above:

X
Y
Z
VinnyD
  • 3,500
  • 9
  • 34
  • 48

3 Answers3

3
$parts = explode('/', trim($url, '/'));
$lastpart = end($parts);

No need for regex. But if you insist:

#^/?([^/]+)/?$#

Path part is in group 1.

Francis Avila
  • 31,233
  • 6
  • 58
  • 96
1

Rather than a regex, use strrpos() to find the last / after trimming off the trailing /:

$string = "/x/y/";

$string = rtrim($string, "/");
echo substr($string, strrpos($string, "/") + 1);
// y

$string = "/x/y/z/";
// prints
// z

$string = "/x";
// prints
// x
Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390
0

I'd go for a preg_split and array_pop:

$test = "a/a/v/";
$test = rtrim($test,'/');
$arr = preg_split('/\//',$test);
$lastelement = array_pop($arr);
var_dump($lastelement);
dotbill
  • 1,001
  • 7
  • 13