需要获得路径的中间部分

I have a path like this

apples/oranges/bananas

I need to get the middle item in the path, in this case oranges.

What is the best way to do it? I can do it myself using strpos and substr but I imagine there is a better way...

$path = explode("/", "apples/oranges/bananas");

echo $path[1];

You could explode the string (assuming it is) and then get the correct index from the array. Like so:

$string = "apples/oranges/bananas";

$array = explode('/', $string);

echo $array[1]; //outputs oranges

If

$path = 'apples/oranges/bananas';

you could do:

$dir = basename(dirname($path));

if you want to start from the end of the string, and should work on Windows, or

$dir = preg_match('|/([^/]*)|', $path, $m) ? $m[1] : false;

if you want to start at the beginning of the string, and will not work on Windows.

Is it always 3 words separated by 2 slashes?
if yes, you can try:

$mypath = explode('/', 'apple/oranges/bananas');
echo $mypath[1]; //gives oranges

Just to show off array dereferencing in PHP > 5.4:

echo explode('/', 'apple/oranges/bananas')[1];