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);
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Dori
  • 18,283
  • 17
  • 74
  • 116

6 Answers6

20

Check out basename().

Daniel Egeberg
  • 8,359
  • 31
  • 44
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.

simplfuzz
  • 12,479
  • 24
  • 84
  • 137
  • 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. – JoshStrange Feb 08 '17 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.

bschaeffer
  • 2,824
  • 1
  • 29
  • 59
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

Scott Saunders
  • 29,840
  • 14
  • 57
  • 64
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.

Curtis
  • 3,931
  • 1
  • 19
  • 26
-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
MakoBuk
  • 622
  • 1
  • 10
  • 19
  • 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 Nov 05 '19 at 12:13
  • @NicoHaase I have added a method for that. – MakoBuk Jan 23 '20 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 Jan 23 '20 at 13:04