12

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?

1
  • 1
    You’re not doing anything wrong. This function works fine (I just did a copy-paste test). Something is therefore wrong with the code that you are not showing us. Of course, the other answers here are “better” in some sense, but you asked what you’re doing wrong. BTW, I’d have written function strip_extension(string $filename) : string {. Commented Jul 23, 2022 at 2:18

7 Answers 7

26

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

Sign up to request clarification or add additional context in comments.

5 Comments

You beat me to it by 35 seconds :P
Problem is, the OP only has the file name, not the full path to the file.
@dosboy: :blows off fingers and re-holsters them to side: ;-)
Heck, i am ninja'd but i have own examples :)
My bad, I thought pathinfo() only worked with valid paths/files. Owned :x
8

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

Comments

1

This very simple function does the trick:

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

1 Comment

You escape the escape character? Is that necessary?
1

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.

Comments

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

1 Comment

You can just use pathinfo($filename, PATHINFO_EXTENSION) to get a string back instead of needing to call isset() on the array.
0

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

Comments

0

If you have just a filename (without path) and simply want to remove the extension (e.g. .jpeg), you can use strtok :

$filenameWithoutPath = 'example.jpeg';
$filenameWithoutExension = \strtok($filenameWithoutPath, '.');

This will simply remove the part of the string including and after the first dot (.). This is not the purpose that strtok was originally intended for, but it works well in this situation, as well as stripping a query string from a URL (strtok($url, '?')).

I expect this is much more efficient than using pathinfo(), which I think would be overkill in both situations.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.