PHP函数来获取文件扩展名

问题描述:

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;
}

任何人都可以帮助我更改此脚本以使用preg_split(建议由php.net替代)而不是拆分 已经用完了。 此函数获取变量$ filename中任何上传文件的文件扩展名。 p>

  function findExtension($ filename)
 {
 $ filename = strtolower($ filename);  
 $ exts = split(“[/ \\。]”,$ filename); 
 $ n = count($ exts)-1; 
 $ exts = $ exts [$ n]; 
return $ exts;  
} 
  code>  pre> 
  div>

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;
}

You should just use pathinfo instead:

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

echo $path_parts['dirname'], "
";
echo $path_parts['basename'], "
";
echo $path_parts['extension'], "
";
echo $path_parts['filename'], "
"; // since PHP 5.2.0

If the file extension is the only part you want:

function GetExt($filename) {
    return (($pos = strrpos($filename, '.')) !== false ? substr($filename, $pos+1) : '');
}

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.

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);
}

Perhaps something along these lines?

$string = "some/path_to_a_file.txt";
$pattern = preg_split('/\./', $string, -1, PREG_SPLIT_OFFSET_CAPTURE); 

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