开发者

PHP - stripping the extension from a file name string

开发者 https://www.devze.com 2023-03-02 20:58 出处:网络
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.

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($fil开发者_C百科ename,0,$dotpos);
   }
   return $result;
}

Which returns an empty string.

I can't see what I'm doing wrong?


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


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


This very simple function does the trick:

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


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.


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


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

精彩评论

暂无评论...
验证码 换一张
取 消