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

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

Susan Sarandon
Susan SarandonOriginal
2024-12-28 07:30:53293browse

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

Extracting File Names from Paths in PHP

In PHP, the need often arises to retrieve the file name from a full path, particularly when working with directories or manipulating file systems. Let's explore how to achieve this using PHP's powerful functions.

Problem: Retrieving File Name from Full Path

Suppose we have the following full path:

F:Program FilesSSH Communications SecuritySSH Secure ShellOutput.map

And we wish to extract the file name, which is "Output.map."

Solution: Using basename() function

The PHP basename() function provides a concise and convenient way to retrieve the file name from a given path.

Syntax:

basename(path, suffix)

Parameters:

  • path: The full path from which to extract the file name.
  • suffix (optional): If provided, removes the specified suffix from the file name.

Example:

To extract the file name from our example path:

<?php
$path = "F:\Program Files\SSH Communications Security\SSH Secure Shell\Output.map";
$file_name = basename($path);
echo $file_name; // Output: Output.map
?>

Removing File Extension:

The suffix parameter can be used to remove any file extension from the retrieved file name. For instance, to extract "Output" from "Output.map":

<?php
$path = "F:\Program Files\SSH Communications Security\SSH Secure Shell\Output.map";
$file_name_without_extension = basename($path, ".map");
echo $file_name_without_extension; // Output: Output
?>

By leveraging PHP's basename() function, developers can efficiently extract file names from full paths with ease and flexibility. This capability is especially useful in a wide range of file management and manipulation scenarios.

The above is the detailed content of How Can I Extract a Filename from a Full Path in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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