Striping the file extension is valuable on many levels.
<?php
$filename = foobar.exe
function returnFileName($fileName) {return key(explode(“.”, $fileName));
}
// returns foobarfunction returnFileExtension($fileName) {
return end(explode(“.”, $fileName));
}
// returns exe
?>
Result: foobar
Note: Spaces count, so count them!
6 comments ↓
If you found this post useful click the share this button. Contribute below by adding a comment, no registration is required.
DCE's Most Talked About Posts
Read Full Article...
Read Full Article...
Read Full Article...
What if the file extension is only 2 character long?
just use $my_file= substr($my_file, 0 , -3);
if you don’t know how long the extension is, you will need to explode the string at the ‘.’, then add them back together except for the final part of the array (sizeof -1)
Funny… lol,
You can remove the file extension even if it’s 100 characters long with this,
$no_extension = implode(‘.’, explode(‘.’, $filename, -1));
Of course there is better, just think about it…
Or you can use pathinfo( ) which is part of php since ver 4
$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
The above example will output:
/www/htdocs/inc
lib.inc.php
php
lib.inc
for more info see: http://php.net/manual/en/function.pathinfo.php
Unfortunately PHP’s pathinfo() doesn’t remove all the extensions if a filename has many extensions such as file.inc.php, for that purpose use the following:
$fileArray = explode(“.”, $filename);
return($fileArray[0]);
Leave a Comment