Get file extension

I explode on "." to get the file format and name:

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

The problem is that some files have names with dots.

How can I use LAST? ". so I get $name=pic.n2 and $ext=jpg from: pic.n2.jpg ?

+6
source share
9 answers

Use pathinfo :

 $pi = pathinfo($name); $txt = $pi['filename']; $ext = $pi['extension']; 
+15
source
 $name = pathinfo($file, PATHINFO_FILENAME); $ext = pathinfo($file, PATHINFO_EXTENSION); 

http://www.php.net/pathinfo

+11
source

use this

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

thanks

+5
source

Use the PHP function pathinfo ().

More details here http://php.net/manual/en/function.pathinfo.php

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

Example:

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

Exit:

PHP 123.test

+1
source

Use Pathinfo or mime_content_type to get file type information

 $filetype = pathinfo($file, PATHINFO_FILENAME); $mimetype = mime_content_type($file); 
+1
source
 <?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; ?> 
+1
source

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;

}

0
source

You can 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 (in this case ".") And substr (), which returns a substring. You find the last "." in the file, and sub is the string. Hope this helps.

0
source

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

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

Which solution does the following:
1. the return line, so it will look like this: txe.eman.elif.emos
2. Blast it, you get something like: $ ext = "txe", $ name = "eman.elif.emos"
3. Cut each variable to get the correct results.

0
source

Source: https://habr.com/ru/post/910137/


All Articles