hamburger
hamburger

Reputation: 1435

get filename out of string

I do have the following strings of files.

/img/studio/record.JPG
/img/studio/view.JPG
/img/studio/doors.JPG
img/team/andy.jpg
img/team/jim.jpg

Now I would like to get only the filename to look in a db.

like: record.JPG

What the best way to get it? (I need a php solution.)

Thanks for any help in advance.

Upvotes: 2

Views: 144

Answers (5)

user2042994
user2042994

Reputation:

I think the basename function should do what you need:

<?php 
echo basename("/img/studio/record.JPG");
?>

returns

record.JPG

Upvotes: 0

HamZa
HamZa

Reputation: 14931

I though of provinding multiple ways to provide the same result:

$str = '/img/studio/record.JPG';

echo basename($str);
echo pathinfo($str, PATHINFO_BASENAME);
echo explode('/', $str)[count(explode('/', $str))-1];
echo strrev(explode("/", strrev($str))[0]);
echo preg_replace('/.*\//', '', $str);

Upvotes: 1

kamituel
kamituel

Reputation: 35970

Use pathinfo (docs):

$path = pathinfo('/img/studio/record.JPG');
echo $path['basename'];     // record.JPG

This way you can easily get directory name or file extension as well:

echo $path['dirname'];      // /img/studio
echo $path['extension'];    // JPG

Upvotes: 2

Jhonathan H.
Jhonathan H.

Reputation: 2713

try pathinfo()

pathinfo('/img/studio/record.JPG', PATHINFO_BASENAME)

Upvotes: 3

Eun
Eun

Reputation: 4178

Use basename:

echo basename('/img/studio/record.JPG');

will return record.JPG.

Upvotes: 4

Related Questions