I want to strip the extension from a filename, and get the file name - e.g. file.xml -> file, image.jpeg -> image, test.march.txt -> test.march, etc.
So I wrote this function
function strip_extension($filename) {
$dotpos = strrpos($filename, ".");
if ($dotpos === false) {
$result = $filename;
}
else {
$result = substr($filename,0,$dotpos);
}
return $result;
}
Which returns an empty string.
I can't see what I'm doing wrong?
The basename function is an inbuilt PHP function mainly used to return the base name of a given file on a certain condition when the path of the desired file is given as a parameter inside the base name function. i.e., it gives the trailing name of the path. Syntax: String basename ( $ path , $ suffix )
$extension = pathinfo ( $file_name , PATHINFO_EXTENSION); echo $extension ; ?> Using end() function: It explodes the file variable and gets the last array element to be the file extension.
Looking for pathinfo
i believe. From the manual:
<?php
$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
?>
Result:
/www/htdocs/inc
lib.inc.php
php
lib.inc
Save yourself a headache and use a function already built. ;-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With