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);
1
  • check out: strrchr() on php.net, or use basename as suggested
    – gblazex
    Commented Jun 30, 2010 at 14:08

6 Answers 6

20

Check out basename().

0
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.

1
  • 3
    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. Commented Feb 8, 2017 at 14:43
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.

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

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.

1
  • Or you could use basename(), like they said. That's better.
    – Curtis
    Commented Jun 30, 2010 at 14:08
-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
3
  • Please add some explanation to your answer. To me, it does not look like you can simply remove a file extension with it
    – Nico Haase
    Commented Nov 5, 2019 at 12:13
  • @NicoHaase I have added a method for that.
    – MakoBuk
    Commented Jan 23, 2020 at 13:03
  • 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?
    – Nico Haase
    Commented Jan 23, 2020 at 13:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.