Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract filename with extension from filepath string

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);
like image 237
Dori Avatar asked Jun 30 '10 14:06

Dori


People also ask

How do I separate filenames and extensions in Python?

The function splitext() in os. path allows you to separate the root and extension of a specified file path. A tuple made up of the root string and the extension string is the function's output.

How do you segregate a basename and extension of a file in Linux?

Sometimes the users need to read the basename of the file only by removing the file extension. Filename and extension can be separated and stored on different variables in Linux by multiple ways. Bash built-in command and shell parameter expansion can be used to remove the extension of the file.


2 Answers

Check out basename().

like image 92
Daniel Egeberg Avatar answered Sep 28 '22 10:09

Daniel Egeberg


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.

like image 36
simplfuzz Avatar answered Sep 28 '22 10:09

simplfuzz