Extract filename with extension from filepath string
Asked Answered
J

6

13

I am looking to get the filename from the end of a filepath string, say

$text = "bob/hello/myfile.zip";

I want to be able to obtain the file name, which I guess would involve getting everything after the last slash as a substring. Can anyone help me with how to do this is PHP? A simple function like:

$fileName = getFileName($text);
Jehanna answered 30/6, 2010 at 14:2 Comment(1)
check out: strrchr() on php.net, or use basename as suggestedUncouple
C
20

Check out basename().

Clamper answered 30/6, 2010 at 14:3 Comment(0)
W
13

For more general needs, use negative value for start parameter.
For e.g.

<?php
$str = '001234567890';
echo substr($str,-10,4);
?>

will output
1234

Using a negative parameter means that it starts from the start'th character from the end.

Wapiti answered 3/1, 2013 at 6:55 Comment(1)
While other questions solve the real problem the OP had this answers the question in the title perfectly. Thank you, I was pretty sure I just needed to use negative number but wanted confirmation.Susanasusanetta
A
11
$text = "bob/hello/myfile.zip";
$file_name = end(explode("/", $text));
echo $file_name; // myfile.zip

end() returns the last element of a given array.

Afterdamp answered 30/6, 2010 at 14:8 Comment(0)
L
1

As Daniel posted, for this application you want to use basename(). For more general needs, strrchr() does exactly what the title of this post asks.

http://us4.php.net/strrchr

Latish answered 30/6, 2010 at 14:8 Comment(0)
C
0

I suppose you could use strrpos to find the last '/', then just get that substring:

$fileName = substr( $text, strrpos( $text, '/' )+1 );

Though you'd probably actually want to check to make sure that there's a "/" in there at all, first.

Clausen answered 30/6, 2010 at 14:7 Comment(1)
Or you could use basename(), like they said. That's better.Clausen
M
-2
function getSubstringFromEnd(string $string, int $length)
{
    return substr($string, strlen($string) - $length, $length);
}

function removeSubstringFromEnd(string $string, int $length)
{
    return substr($string, 0, strlen($string) - $length);
}

echo getSubstringFromEnd("My long text", 4); // text
echo removeSubstringFromEnd("My long text", 4); // My long
Microhenry answered 5/11, 2019 at 9:35 Comment(3)
Please add some explanation to your answer. To me, it does not look like you can simply remove a file extension with itCrowson
@NicoHaase I have added a method for that.Microhenry
How does that code work? What about file extensions that are not four characters long? If the length of that extension is not known before calling one of your magic functions, how is that supposed to work?Crowson

© 2022 - 2024 — McMap. All rights reserved.