phpregexmaterialized-path-pattern

Materialized Path PHP Regex to Select Last Item


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

Solution

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

    No need for regex. But if you insist:

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

    Path part is in group 1.