2

Can anyone help me change this script to use preg_split (recommended substitute by php.net) instead of split which is not used anymore. This function gets the file extension of any uploaded file in the variable $filename.

function findExtension ($filename)
{
   $filename = strtolower($filename) ;
   $exts = split("[/\\.]", $filename) ;
$n = count($exts)-1;
$exts = $exts[$n];
return $exts;
}
imbayago
  • 501
  • 1
  • 7
  • 22

7 Answers7

16

You should just use pathinfo instead:

$path_parts = pathinfo('/www/htdocs/inc/lib.inc.php');

echo $path_parts['dirname'], "\n";
echo $path_parts['basename'], "\n";
echo $path_parts['extension'], "\n";
echo $path_parts['filename'], "\n"; // since PHP 5.2.0
onteria_
  • 68,181
  • 7
  • 71
  • 64
2

Why don't u use this function : http://www.php.net/manual/fr/function.finfo-file.php or this one : http://fr2.php.net/manual/fr/function.pathinfo.php

you can also use explode

function findExtension ($filename)
{
   $filename = strtolower($filename) ;
   $exts = explode(".", $filename) ;
   $n = count($exts)-1;
   $exts = $exts[$n];
   return $exts;
}
Brice Favre
  • 1,511
  • 1
  • 15
  • 34
2

Instead of split you can just use explode. As you just want the extension, there's no reason to split by /, just split by the dot and get the last element with array_pop.

jeroen
  • 91,079
  • 21
  • 114
  • 132
2

I prefer a function David Walsh posted, that uses the "strrchr" function to get the last occurrence of "." in a string.


function get_file_extension($file_name)
{
  return substr(strrchr($file_name,'.'),1);
}
Mark Fruhling
  • 596
  • 6
  • 18
1

If the file extension is the only part you want:

function GetExt($filename) {
    return (($pos = strrpos($filename, '.')) !== false ? substr($filename, $pos+1) : '');
}
steveo225
  • 11,394
  • 16
  • 62
  • 114
0

My code will give file extension, removing query strings. pathinfo also return extension with string. so use my code if you want to know the exact file name:

$filename = 'http://doamin/js.jquery.min.js?v1.1.11';    
preg_replace('/\?.*/', '', substr(strrchr($filename, '.'), 1));

// output: js
user007
  • 3,203
  • 13
  • 46
  • 77
0

Perhaps something along these lines?

$string = "some/path_to_a_file.txt";
$pattern = preg_split('/\./', $string, -1, PREG_SPLIT_OFFSET_CAPTURE); 
Swift
  • 13,118
  • 5
  • 56
  • 80