Home > Backend Development > PHP Tutorial > How Can I Extract a Filename from a Full File Path in PHP?

How Can I Extract a Filename from a Full File Path in PHP?

Barbara Streisand
Release: 2024-12-17 20:29:09
Original
185 people have browsed it

How Can I Extract a Filename from a Full File Path in PHP?

PHP: Extracting File Names from Complete Paths

Obtaining the file name alone from a full file path is a common task when working with file systems. In PHP, this can be accomplished using the basename() function.

Example:

Consider the following file path:

F:\Program Files\SSH Communications Security\SSH Secure Shell\Output.map
Copy after login

Objective: Extract the file name "Output.map" from the path.

Solution:

The basename() function takes a file path as an input and returns the file name. The following code snippet demonstrates its usage:

$path = "F:/Program Files/SSH Communications Security/SSH Secure Shell/Output.map";
$filename = basename($path);

echo $filename; // Output: Output.map
Copy after login

Additional Notes:

  • The basename() function can optionally take a second argument to specify a suffix to remove from the file name. For instance, to extract just the file name without the extension, you can use:
$filename = basename($path, ".map"); // Output: Output
Copy after login
  • The basename() function works for directories as well, returning the directory name instead of the file name.

The above is the detailed content of How Can I Extract a Filename from a Full File Path 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