Joe
Joe

Reputation: 15802

Regex - Match all subsections

I have the following strings which indicate a hierarchy:

JHW/1/24/3/562 // child row
JHW/1/24/3     // parent of the above
JHW/1/24       // parent of the above
JHW/1          // parent of the above
JHW            // parent of the above

What I'd like to do is to be able to pull out all of the "parent" rows with one regex.

The closest I've got conceptually (which isn't anywhere near) is #^([^/]*/)+# which just matches the second-last section [eg. 3].

I've never really tried to do something like this before, where I'm trying to get overlapping results - it is possible? It's not an issue if it brings back the child row as one of the matches.

Upvotes: 0

Views: 57

Answers (1)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89557

You can't obtain several results from the same position (since the regex engine go to the next character after each try of the pattern), you can explode the string with / and build each path you need with the array items.

An other possible way consists to reverse the string:

preg_match_all('~(?=(?:\A|/)(.+))~', strrev($path), $m);

$result = array_map('strrev', $m[1]);

Upvotes: 2

Related Questions