Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: filename without file extension- best way?

Tags:

php

I am trying to pull the filename out of a directory without the extension.

I am kludging my way through with the following:

foreach ($allowed_files as $filename) { 
  $link_filename = substr(basename($filename), 4, strrpos(basename($filename), '.'));
  $src_filename = substr($link_filename, 0, strrpos($link_filename) - 4);
  echo $src_filename;
}

...But that can't work if the extension string length is more than 3. I looked around in the PHP docs to no avail.

like image 803
jml Avatar asked Jan 03 '10 03:01

jml


People also ask

How do I name a file without an extension?

GetFileNameWithoutExtension(ReadOnlySpan<Char>) Returns the file name without the extension of a file path that is represented by a read-only character span.

How can I download PHP file without extension?

Just use readfile on the local path to the file, and it'll be fine, or use die(file_get_contents($imgPath)) instead of the last line to circumvent PHP's native behaviour.

What extension should a PHP file have?

php file extension refers to the name of a file with a PHP script or source code that has a ". PHP" extension at the end of it. It's similar to a Word file with a . doc file extension.


2 Answers

PHP has a handy pathinfo() function that does the legwork for you here:

foreach ($allowed_files as $filename) {
  echo pathinfo($filename, PATHINFO_FILENAME);
}

Example:

$files = array(
  'somefile.txt',
  'anotherfile.pdf',
  '/with/path/hello.properties',
);

foreach ($files as $file) {
  $name = pathinfo($file, PATHINFO_FILENAME);
  echo "$file => $name\n";
}

Output:

somefile.txt => somefile
anotherfile.pdf => anotherfile
/with/path/hello.properties => hello
like image 135
cletus Avatar answered Oct 21 '22 14:10

cletus


try this

function file_extension($filename){
    $x = explode('.', $filename);
    $ext=end($x);
    $filenameSansExt=str_replace('.'.$ext,"",$filename);
    return array(
        "filename"=>$filenameSansExt,
        "extension"=>'.'.$ext,
        "extension_undotted"=>$ext
        );
}

usage:

$filenames=array("file1.php","file2.inc.php","file3..qwe.e-rt.jpg");
foreach($filenames as $filename){
    print_r(file_extension($filename));
    echo "\n------\n";

}

output

Array
(
    [filename] => file1
    [extension] => .php
    [extension_undotted] => php
)

------
Array
(
    [filename] => file2.inc
    [extension] => .php
    [extension_undotted] => php
)

------
Array
(
    [filename] => file3..qwe.e-rt
    [extension] => .jpg
    [extension_undotted] => jpg
)

------
like image 26
ekhaled Avatar answered Oct 21 '22 15:10

ekhaled