cherryBom
cherryBom

Reputation: 73

How to extract only subdirectory name?

Let's say path to my photo is: /images/nature/photo.jpg and I want to get only nature. What should I do? I tried dirname but it returns /images/nature

Upvotes: 0

Views: 135

Answers (2)

u_mulder
u_mulder

Reputation: 54831

Solution for any numbers of directories:

$str = "/images/nature/photo.jpg";
print_r(basename(dirname($str)));

$str = "/images/nature/sub-nature/photo.jpg";
print_r(basename(dirname($str)));

Upvotes: 1

Hassaan Ali
Hassaan Ali

Reputation: 1061

let's say the url you're getting is in string. Then you can do the following to get the "nature" from the url.

<?php
$str = "/images/nature/photo.jpg";
$brk = explode("/",$str);
print_r($brk[2]);
?> 

Upvotes: 2

Related Questions