PHP, Get File Name Without File Extension

PHP, get file name without file extension

No need for all that. Check out pathinfo(), it gives you all the components of your path.

Example from the manual:

$path_parts = pathinfo('/www/htdocs/index.html');

echo $path_parts['dirname'], "\n";
echo $path_parts['basename'], "\n";
echo $path_parts['extension'], "\n";
echo $path_parts['filename'], "\n"; // filename is only since PHP 5.2.0

Output of the code:

/www/htdocs
index.html
html
index

And alternatively you can get only certain parts like:

echo pathinfo('/www/htdocs/index.html', PATHINFO_EXTENSION); // outputs html

PHP: filename without file extension- best way?

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

PHP: Get filename (without extension) of uploaded file without knowing its path?

This should do the trick:

echo basename(__FILE__, '.php');

edit
My excuse, did not read it good.

pathinfo($filename, PATHINFO_FILENAME) 

should to the trick!

file name without extension

$filename = pathinfo($_FILES['file']['name'], PATHINFO_FILENAME);

pathinfo is a core PHP function since 4.0.3, and the PATHINFO_FILENAME option was added in 5.2.

PHP Fetch current page name without extension?

Everyone loves one-liners:

ucfirst(pathinfo($_SERVER['PHP_SELF'], PATHINFO_FILENAME))

The second argument to pathinfo() strips the path and extension from the file name (PHP >= 5.2)

Btw, I'm using $_SERVER['PHP_SELF'] instead of __FILE__ because otherwise it would break if the code is ran from another file ;-)



Related Topics



Leave a reply



Submit