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 everyth开发者_如何学Cing 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);
Check out basename()
.
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.
$text = "bob/hello/myfile.zip";
$file_name = end(explode("/", $text));
echo $file_name; // myfile.zip
end()
returns the last element of a given array.
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
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.
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
精彩评论