How to Extract a file extension in PHP

In programming practices we usually use different code to achieve something. But we always find what is the best way to do :).

Similarly for extract file extension in PHP we seen various script to achieve this. I am going to explain all ways to do this . In below example I explain five type of script to extract file extension in php.

In ‘banner.jpg‘ we want to extract file extension ‘jpg’ here.

$fileName = 'banner.jpg';

Script 1:-  explode file variable and get last element of array it will be the file extension.

$ext = end(explode('.', $fileName));

Script 2:- Find the last occurrence of ‘.’ in a file name it will return ‘.jpg’ and then remove first character of a string using substr(strrchr($fileName, ‘.’), 1) it will return exact file extension ‘.jpg’

$ext = substr(strrchr($fileName, '.'), 1);

Script 3:- In third approach we using strrpos to find the position of the last occurrence of a ‘.’ in a file name and increment that position by 1 so that it will explode string from (.)

$ext = substr($fileName, strrpos($fileName, '.') + 1);

Script 4:-    In preg_replace approach we using regular expression search and replace. In preg_replace function first parameter is pattern to the search, second parameter $1 is a reference to whatever is matched by the first (.*) and third parameter is file name.

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

Script 5:-
Now its time to know about pathinfo() php function, pathinfo() returns information about a file. If second optional parameter are not passed then it will return associative array containing dirname, basename, extension and filename. If second paramter passed then it will return specific information (As in below example we haved passed PATHINFO_EXTENSION to get file extension)

$fileName = 'banner.jpg';
$ext = pathinfo($fileName, PATHINFO_EXTENSION);

So in my opinion avoid string operation and regular expression match to extract extension. It would be better to use pathinfo() function to extract extension in php.

(Visited 2,044 times, 42 visits today)