Materialized Path PHP Regex to Select Last Item

502 views Asked by At

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
3

There are 3 answers

0
Francis Avila On BEST ANSWER
$parts = explode('/', trim($url, '/'));
$lastpart = end($parts);

No need for regex. But if you insist:

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

Path part is in group 1.

0
Michael Berkowski On

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
0
dotbill On

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);