Oihana PHP

getFileExtension.php

Table of Contents

Functions

getFileExtension()  : string|null
Retrieves the file extension (including multipart extensions) from a given file path.

Functions

getFileExtension()

Retrieves the file extension (including multipart extensions) from a given file path.

getFileExtension(string $file[, array<string|int, mixed>|null $multiplePartExtensions = null ][, bool $lowercase = true ]) : string|null

This function extracts the file extension from the filename portion of the path, supporting both simple extensions (e.g. .txt) and multipart extensions (e.g. .tar.gz, .blade.php). It relies on the getBaseFileName() function to determine the filename without its extension, then returns the remainder as the extension.

The function normalizes Windows-style backslashes (\) to forward slashes (/) before processing.

Parameters
$file : string

The full path or filename from which to extract the extension.

$multiplePartExtensions : array<string|int, mixed>|null = null

Optional array of multipart extensions to consider. If null, the default set from FileExtension::getMultiplePartExtensions() is used.

$lowercase : bool = true

Enforce the extension to be lowercase (default true).

Tags
example

Basic usage: extract extension from a file path.

use function oihana\files\getFileExtension;

echo getFileExtension('/path/to/archive.tar.gz');    // .tar.gz
echo getFileExtension('photo.JPG');                  // .jpg (lowercased by default)
echo getFileExtension('/some/file.txt');             // .txt
echo getFileExtension('/templates/home.blade.php');  // .blade.php
echo getFileExtension('script.min.js');              // .js

Using custom multipart extensions:

$custom = ['.custom.ext', '.tpl.php'];

echo getFileExtension('file.custom.ext', $custom);   // .custom.ext
echo getFileExtension('file.tpl.php', $custom);      // .tpl.php

Preserving original case:

echo getFileExtension('README.MD', null, false);     // .MD

Files with no extension:

echo getFileExtension('Makefile');                   // null
echo getFileExtension('.env');                       // null

Windows-style path normalization:

echo getFileExtension('C:\\projects\\demo.tar.bz2'); // .tar.bz2

Edge case: file with multiple dots and unknown multipart extension:

echo getFileExtension('data.backup.final.bak');      // .bak
author

Marc Alcaraz (ekameleon)

since
1.0.0
Return values
string|null

The file extension including the leading dot (e.g. .tar.gz), or null if the file has no extension.


        
On this page

Search results