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
Release: 2024-12-28 07:30:53
Original
282 people have browsed it

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

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

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

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!

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