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
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]
Link to comment
Share on other sites

[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
Link to comment
Share on other sites

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]
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.