-1
$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];

I have trouble undertand the step 5, anyone able to explain? And also What does it mean by never use approach?

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
apple
  • 13
  • 3
  • 1
    If your [previous question along similar lines](http://stackoverflow.com/questions/9251707/removing-extensions-from-filename) was closed as an exact duplicate, perhaps you should use the answer from the specified duplicate question's answer or the highly upvoted first comment from your previous question? –  Feb 12 '12 at 19:20
  • I kind of disagree that this is a duplicate. The OP is asking for an explanation of a specific implementation here as commented in the code above... – Michael Berkowski Feb 12 '12 at 19:23
  • I agree too -- I don't think it's a duplicate. It's a valid question, just wondering aloud why the OP is still messing with it. I'd like to rescind the (overly hasty) close vote, but my original comment still stands. –  Feb 12 '12 at 19:25

2 Answers2

2

The most glaringly obvious reason not to use this method is that the split() function is deprecated in PHP 5.3, and will be removed in later versions. It should not be used since the function will go away.

Furthermore, if the filename has no extension, you'll get an Undefined index notice when attempting to access the extension from $exts[$n] since $exts[-1] isn't set. That would happen because the $exts array is empty (count($exts) === 0) when there's no . in the filename, but the code doesn't account for that possibility.

Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390
0

All these approaches, and you're missing the built-in function:

$filename = 'mypic.gif';
$extension = pathinfo($filename,PATHINFO_EXTENSION);
var_dump($extension);

This doesn't directly answer your question about approach number #5... but why are you messing about with all these methods and ignoring what PHP explicitly provides to do this for you?

Mark Baker
  • 209,507
  • 32
  • 346
  • 385