Home >Backend Development >PHP Tutorial >How Can I Extract Filenames from File Paths in PHP?
Accessing Filenames from Path Strings in PHP
When working with files in PHP, it's often necessary to extract just the filename from a full file path. This is where the basename() method comes in handy.
Retrieving Filenames Using basename()
The basename() method takes a file path as an argument and returns the filename component alone. Consider the following example:
$path = "F:\Program Files\SSH Communications Security\SSH Secure Shell\Output.map"; $filename = basename($path);
In this case, the $filename variable will be assigned the string "Output.map". The basename() method effectively stripped away the directory path component, leaving only the file's name.
Stripping File Extensions
Additionally, you can use the basename() method to remove the file extension from the file path. To do this, provide a second argument to the method, indicating the extension to remove.
For instance, if you want to extract the filename without the ".map" extension from the example above, you would use:
$path = "F:\Program Files\SSH Communications Security\SSH Secure Shell\Output.map"; $filename = basename($path, ".map"); // Remove the ".map" extension
The $filename variable will now be set to "Output".
The above is the detailed content of How Can I Extract Filenames from File Paths in PHP?. For more information, please follow other related articles on the PHP Chinese website!