Get File Extension Using PHP

There are several ways to grab file extension (E.g, 'txt' from 'my.txt') using PHP. You can use anyone from flowing. But I prefer to use pathinfo function, because it is PHP's build in function to grab file path information and others are string functions.

1. Using end>explode Function:
$ext = end(explode('.', $filename));

2. Using substr>strrchr Function:
$ext = substr(strrchr($filename, '.'), 1);

3. Using preg_replace Function:
$ext = preg_replace('/^.*\.([^.]+)$/D', '$1', $filename);

Finally pathinfo Function (PHP Build in Function to Grab File Path Information):
$ext = pathinfo($filename, PATHINFO_EXTENSION);


Go to top