Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - stripping the extension from a file name string

Tags:

string

php

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?

like image 432
boisvert Avatar asked May 05 '11 13:05

boisvert


People also ask

What is Basename PHP?

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 )

How can I get file extension in PHP?

$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.


1 Answers

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

like image 168
Brad Christie Avatar answered Oct 13 '22 09:10

Brad Christie