Skip to content
Related Articles

Related Articles

How to extract extension from a filename using PHP ?

Improve Article
Save Article
Like Article
  • Difficulty Level : Expert
  • Last Updated : 06 Dec, 2021

In this article, we will see how to extract the filename extension in PHP, along with understanding their implementation through the examples. There are a few different ways to extract the extension from a filename with PHP, which is given below:

Using pathinfo() function: This function 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.

Example: This example describes the use of the pathinfo() function that returns information about a path using an associative array or a string. 

PHP




<?php
  $file_name = 'gfg.html';
  $extension = pathinfo($file_name, PATHINFO_EXTENSION);
  echo $extension;
?>


Output

html

Using end() function: It explodes the file variable and gets the last array element to be the file extension. The PHP end() function is used to get the last element of the array.

Example: This example describes the use of the end() function that is used to find the last element of the given array.

PHP




<?php
  $file_name = 'gfg.html';
  $temp= explode('.',$file_name);
  $extension = end($temp);
  echo $extension;
?>


Output

html

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.

Example: This example uses both substr()  function & strchr() function. 

PHP




<?php
  $file_name = 'gfg.html';
  $extension = substr(strrchr($file_name, '.'), 1);
  echo $extension;
?>


Output

html

Using strrpos() function: This function is used to find the last occurrence position of a ‘.’ in a filename and enhances the file position by 1 to explode string (.)

Example: This example describes the use of the strrpos() function that finds the position of the last occurrence of a string in another string. 

PHP




<?php
  $file_name = 'gfg.html';
  $extension = substr($file_name, strrpos($file_name, '.') + 1);
  echo $extension;
?>


Output

html

Using preg_replace() function: Using regular expressions like replace and search. The first parameter of this 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.

Example: This example uses the preg_replace() function to perform a regular expression for search and replace the content.

PHP




<?php
  $file_name = 'gfg.html';
  $extension = preg_replace('/^.*\.([^.]+)$/D', '$1', $file_name);
  echo $extension;
?>


Output

html

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!