-4

How to find the extension of given file name:

See code below:

$file_name = "sample.jpg";

Output will be: .jpg

I need to find the extension of the file name

Example: If we parse sample.jpg i should return .jpg

Nes
  • 304
  • 1
  • 10

3 Answers3

0

You can try with explode

    $file_name = "sample.jpg";
    $pieces = explode(".", $file_name);
    echo $pieces[0]; // sample
    echo '.'.$pieces[count($pieces)-1]; // .jpg

You can also use this:

$ext = pathinfo($file_name, PATHINFO_EXTENSION);
echo $ext;//jpg
Suvash sarker
  • 3,140
  • 1
  • 18
  • 21
0

Here one way to find:

<?php
$filename = "sample.txt.jpg";
$ext = substr($filename, strrpos($filename, "."));
echo $ext;
?>
Nes
  • 304
  • 1
  • 10
0

Use PHP SPL class to find any info about a file. more detail read here

$file = new SplFileInfo($path);
$ext  = $file->getExtension();
Praveen D
  • 2,337
  • 2
  • 31
  • 43