Home >Backend Development >PHP Tutorial >How to Extract a Filename Without Its Extension in PHP?

How to Extract a Filename Without Its Extension in PHP?

Barbara Streisand
Barbara StreisandOriginal
2024-11-11 18:03:03437browse

How to Extract a Filename Without Its Extension in PHP?

Getting Filename Without Extension in PHP

Problem:

When working with PHP scripts, you may need to access the filename of the currently executed script. However, this filename typically includes the ".php" extension. How can you extract just the filename without this extension?

Answer:

To obtain the current filename with its extension, you can use the magic constant __FILE__ in PHP. However, if you desire to exclude the ".php" extension from the result:

  1. Using __FILE__ Constant:
$filename = basename(__FILE__, '.php');
  1. Generic File Extension Remover Function:
function chopExtension($filename) {
    return pathinfo($filename, PATHINFO_FILENAME);
}
  1. Using Standard String Library Functions:
function chopExtension($filename) {
    return substr($filename, 0, strrpos($filename, '.'));
}

These functions can be applied to filenames with any extension, not just ".php" files.

The above is the detailed content of How to Extract 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