Thursday 12 July 2012

How to Get File Extension in php?

To make things a little clearer for people who can visualise code more easily than paragraphs of text, here are a few examples of what I’ve seen used in the past. The samples are mostly compacted onto a single line but if you’re not comfortable with multiple things happening in one line, feel free to expand them into multiple steps. In all cases, $ext ends up being “gif” .


$filename = 'mypic.gif';

// 1. The "explode/end" approach
$ext = end(explode('.', $filename));

// 2. The "strrchr" approach
$ext = substr(strrchr($filename, '.'), 1);

// 3. The "strrpos" approach
$ext = substr($filename, strrpos($filename, '.') + 1);

// 4. The "preg_replace" approach
$ext = preg_replace('/^.*\.([^.]+)$/D', '$1', $filename);

// 5. The "never use this" approach
//   From: http://php.about.com/od/finishedphp1/qt/file_ext_PHP.htm
$exts = split("[/\\.]", $filename);
$n = count($exts)-1;
$ext = $exts[$n];

No comments:

Post a Comment

Note: only a member of this blog may post a comment.