How To Extract Extension From Filename Using PHP?

03-Apr-2023

.

Admin

How To Extract Extension From Filename Using PHP?

Hi Dev,

There are a few different ways to extract the extension from a filename with PHP.

This example is base to php different ways to extract the extension from a filename with PHP.

This is a simple way and easy short code example.

So let's start example following step.

Example : 1


Using pathinfo(): The pathinfo() is a function that returns information about a file. If the second optional parameter is omitted, an associative array containing dirname, basename, extension, and the filename will be returned. If the second parameter is true, it will return specific data.

<?php

$file_name = 'nicesnippets.pdf';

$extension = pathinfo($file_name, PATHINFO_EXTENSION);

echo $extension;

?>

Output:

pdf

Example : 2

Explode the file variable and get the last array element to be the file extension. The PHP end() function is used to get the last element of the array.

<?php

$file_name = 'index.html';

$temp= explode('.',$file_name);

$extension = end($temp);

echo $extension;

?>

Output:

html

Example : 3

Using substr() and strrchr() functions:

substr(): A part of the string is returned.

strrchr(): The last occurrence of a string inside another string is determined.

<?php

$file_name = 'index.html';

$extension = substr(strrchr($file_name, '.'), 1);

echo $extension;

?>

Output:

html

Example : 4

Using strrpos() to find the last occurrence position of a ‘.’ in a filename and enhance the file position by 1 to explode string (.)

<?php

$file_name = 'index.html';

$extension = substr($file_name, strrpos($file_name, '.') + 1);

echo $extension;

?>

Output:

html

Example : 5

Using regular expressions like replace and search. The first parameter of the preg_replace() function is the search pattern, the second parameter $1 is a reference to whatever matches the first (.*), and the third parameter is the file name.

<?php

$file_name = 'nicesnippets.jpg';

$extension = preg_replace('/^.*\.([^.]+)$/D', '$1', $file_name);

echo $extension;

?>

Output:

jpg

I hope it can be useful....

#PHP 8

#PHP