Home >Backend Development >PHP Tutorial >How Can I Easily Get a Filename Without Its Extension in PHP?

How Can I Easily Get a Filename Without Its Extension in PHP?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-07 00:39:131056browse

How Can I Easily Get a Filename Without Its Extension in PHP?

Getting File Name Without Extension: A Simplified Approach

Your initial code aims to extract the file name without extension, yet it seems overly complex. A simpler solution lies in utilizing PHP's built-in function, pathinfo().

pathinfo() decomposes a file path into its various components, including the filename without extension. For example, the code snippet below demonstrates its usage:

$filename = pathinfo($filepath, PATHINFO_FILENAME);

Here, $filepath represents the file string stored in a variable. The result, $filename, will contain the filename stripped of its extension.

To illustrate further, consider the following example:

$path_parts = pathinfo('/www/htdocs/index.html');

echo $path_parts['dirname'], "\n";
echo $path_parts['basename'], "\n";
echo $path_parts['extension'], "\n";
echo $path_parts['filename'], "\n"; // filename is only since PHP 5.2.0

This code outputs the following:

/www/htdocs
index.html
html
index

As you can see, pathinfo() provides a convenient and efficient way to extract file components, including the filename without extension. It eliminates the need for complex regular expressions and offers a more straightforward approach to file manipulation tasks.

The above is the detailed content of How Can I Easily Get a Filename Without Its Extension 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