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

7 Answers 7

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
Sign up to request clarification or add additional context in comments.

Comments

2

Why don't u use this function : http://www.php.net/manual/fr/function.finfo-file.php or this one : https://www.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;
}

1 Comment

This is an easier way to understand the 'explode' function. Thanks
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.

1 Comment

Seems 'explode' could be file extension finding standard. Thanks
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);
}

Comments

1

If the file extension is the only part you want:

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

Comments

0

Perhaps something along these lines?

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

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.