tags:

views:

67

answers:

4

I am looking to get the substring from the end of a line of text, 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 how to do this is PHP? A simple function like

$fileName = getFileName($text);
+10  A: 

Check out basename().

Daniel Egeberg
excellent thanks, perfect :)
Dori
Genius! Perfecto!
Brad F Jacobs
A: 

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
Or you could use basename(), like they said. That's better.
Curtis
A: 
$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
+1  A: 

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