Home > Backend Development > PHP Tutorial > How Can I Extract Filenames from File Paths in PHP?

How Can I Extract Filenames from File Paths in PHP?

Mary-Kate Olsen
Release: 2024-12-23 18:23:10
Original
1001 people have browsed it

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);
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template