Home » Php » php – Get the file extension

php – Get the file extension

Posted by: admin July 12, 2020 Leave a comment

Questions:

I’m exploding on “.” to get file format and name:

list($txt, $ext) = explode(".", $name);

The problem is that some files have names with dots.

How do I explote on the LAST “.” so that I get $name=pic.n2 and $ext=jpg from: pic.n2.jpg?

How to&Answers:

Use pathinfo:

$pi = pathinfo($name);
$txt = $pi['filename'];
$ext = $pi['extension'];

Answer:

$name = pathinfo($file, PATHINFO_FILENAME);
$ext  = pathinfo($file, PATHINFO_EXTENSION);

http://www.php.net/pathinfo

Answer:

use this

$array = explode(".", $name);
end($array);         // move the internal pointer to the end of the array
$filetype = current($array);

thanks

Answer:

Use Pathinfo or mime_content_type to get file type information

$filetype = pathinfo($file, PATHINFO_FILENAME);

$mimetype = mime_content_type($file);

Answer:

Use PHP’s pathinfo() function.

See more information here http://php.net/manual/en/function.pathinfo.php

$file_part = pathinfo('123.test.php');

Example:

echo $file_part['extension'];
echo $file_part['filename'];

Output:

php
123.test

Answer:

<?php
$path = 'http://www.mytest.com/public/images/portfolio/i-vis/abc.y1.jpg';
echo $path."<br/>";
$name = basename($path);
$dir = dirname($path); 
echo $name."<br/>";
echo $dir."<br/>";
$pi = pathinfo($path);
$txt = $pi['filename']."_trans";
$ext = $pi['extension'];
echo $dir."/".$txt.".".$ext;
?>

Answer:

you can write your own function as

function getExtension($str) {

$i = strrpos($str,".");

if (!$i) { return ""; }

$l = strlen($str) – $i;

$ext = substr($str,$i+1,$l);

return $ext;

}

Answer:

You might try something like this:

<?php
$file = 'a.cool.picture.jpg';

$ext = substr($file, strrpos($file, '.')+1, strlen($file)-strrpos($file, '.'));
$name = substr($file, 0, strrpos($file, '.'));
echo $name.'.'.$ext;
?>

The key functions are strrpos() which finds the last occurrence of a character (a “.” in this case) and substr() which returns a sub string. You find the last “.” in the file, and sub string it. Hope that helps.

Answer:

It is better to use one of the solutions above, but there is also a solution using the explode function:

$filename = "some.file.name.ext";
list($ext, $name) = explode(".", strrev($filename), 2);
$name = strrev($name);
$ext = strrev($ext);

What this solution does is the following:
1. reverse string, so it will look like: txe.eman.elif.emos
2. explode it, you will get something like: $ext = “txe”, $name = “eman.elif.emos”
3. reverse each of the variables to get the correct results