Jump to content

Separate extension from filename


papaface

Recommended Posts

Hello,
I have seen this type of topic answered before but I cant seem to find it.
Therefore could someone kindy tell me how I would go about separating the extension from the filename, AND have the ability to echo them both out.

Currently I have:
[code]
$filename = pathinfo("text.txt")
echo $filename["extension"];
echo $filename["filename"];
[/code]
But this doesnt work on some versions of mysql/php.

Thanks.
Link to comment
https://forums.phpfreaks.com/topic/29992-separate-extension-from-filename/
Share on other sites

I get
[code]Warning: join() [function.join]: Bad arguments. in split.php on line 6[/code]

[code]<?php
$filename = "text.txt";
$filename = explode('.',$filename);
$extension = $filename[count($filename)-1];
$filename = array_pop($filename);
$filename = join('.',$filename);

$fn = $filename[0];

echo $fn;

?>[/code]
[code]
<?php
$filename = "text.txt";

list($the_file_bit, $extension) = explode('.', $filename);

echo "here's the file bit: $the_file_bit and here's the extension: $extension";

// or :
echo $the_file_bit;
echo $extension;
?>
[/code]

have a look at the [url=http://www.php.net/list]list[/url] function. just the ticket for this type of thing.
cheers
Mark
IMO you can't assume

1) that a file has an extension

2) that a file doesn't have more than one dot in it

Here's what I would use:
[code]<?php
function filebits($file){
  $bits = Array( 'name' => NULL, 'ext' => NULL );
  if(strlen($file)){
    $file = explode(".", $file);
    $bits['name'] = $file[0];
    $bits['ext'] = ($num = count($file)) > 1 ? $file[$num - 1] : NULL;
  }
  return $bits;
}
?>[/code]

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.