boisvert
boisvert

Reputation: 3739

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?

Upvotes: 12

Views: 18667

Answers (6)

carlo
carlo

Reputation: 1

Probably not the most efficient, but it actually answers the question.

function strip_extension($filename){
    $f = array_reverse(str_split($filename));
    $e = array();
    foreach($f as $p){
        if($p == '.'){
            break;
        }else{
            array_push($e,$p);
        }
    }
    return implode('',array_reverse($e));
}

Upvotes: 0

function strip_extension($filename){
  if (isset(pathinfo($filename)['extension'])) { // if have ext
    return substr($filename, 0, - (strlen(pathinfo($filename)['extension'] +1)));
  }
  return $filename;  // if not have ext
}

You must verify if the filename has extension to not have errors with pathinfo. As explained in http://php.net/manual/en/function.pathinfo.php

Upvotes: 0

alex
alex

Reputation: 490657

Here is a short one. Just know if you pass a path, you'll lose the path info :)

function stripExtension($filename) {
   return basename($filename, '.' . pathinfo($filename, PATHINFO_EXTENSION));
}

CodePad.

The only real advantage of this one is if you are running < PHP 5.2.

Upvotes: 1

Mathieu Rodic
Mathieu Rodic

Reputation: 6762

This very simple function does the trick:

function strip_extension($filename)
{
    $extension = pathinfo($filename, PATHINFO_EXTENSION);
    $regexp = '@\.'.$extension.'$@';
    return preg_replace($regexp, "", $filename);
}

Upvotes: 1

Robik
Robik

Reputation: 6127

You should use pathinfo which is made to do that.

Example: Things used: pathinfo()

$name = 'file.php';

$pathInfo = pathinfo($name);

echo 'Name: '. $pathInfo['filename'];

Results:

Name: file

Example 2 (shorter)

$name = 'file.php';    
$fileName= pathinfo($name, PATHINFO_FILENAME );

echo "Name: {$fileName}";

Results:

Name: file

Live examples: No. 1 | No. 2

Upvotes: 8

Brad Christie
Brad Christie

Reputation: 101614

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

Upvotes: 25

Related Questions