phpstring

PHP - stripping the extension from a file name string


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?


Solution

  • 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. ;-)