Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

File ext when there is more than one period

Status
Not open for further replies.

NevadaJones

Programmer
Sep 5, 2006
26

What I want to do is pull off the file extension of a file. This works most of the time, but not if a file has more than one period.

$filename_ext = strchr($filename, ".");

How can I get the extension of a file like:

$filename = "this.has.more.than.one.period.ext";


Sam
;
 
I'd probably just explode the filename on the dots and take the last element:

Code:
<?php
$filename = "this.has.more.than.one.period.ext";
print end (explode ('.', $filename));
?>


Want the best answers? Ask the best questions! TANSTAAFL!
 
Just thought I'd make a note for your code's sake that filenames are NOT obligated to have an extension... Hope you've coded for that possibility! :)
D.

D.E.R. Management - IT Project Management Consulting
 
You can also use the strrchr function to find the last occurrence of a character in a string and, seeing as file extensions (when they're present) follow the last period in a filename string, strrchr seems well suited to this application.

Here's some examples with and without the leading period:
Code:
<?php
  $filename = "this.has.more.than.one.period.ext";
  print strrchr($filename, '.');
?>
Code:
<?php
  $filename = "this.has.more.than.one.period.ext";
  $file_ext = strrchr($filename, '.');
  // use substr to omit first character i.e. the period
  print substr($file_ext, 1);
?>
As with anything in programming, there are always many ways to skin a cat!

Clive
Runner_1Revised.gif

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"To err is human, but to really foul things up you need a computer." (Paul Ehrlich)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
To get the best answers from this forum see: faq102-5096
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top