e-satis e-satis - 10 months ago 60
PHP Question

How to extract a file extension in PHP?

This is a question you can read everywhere on the web with various answers :

$ext = end(explode('.', $filename));
$ext = substr(strrchr($filename, '.'), 1);
$ext = substr($filename, strrpos($filename, '.') + 1);
$ext = preg_replace('/^.*\.([^.]+)$/D', '$1', $filename);

$exts = split("[/\\.]", $filename);
$n = count($exts)-1;
$ext = $exts[$n];


However, there is always "the best way" and it should be on stackoverflow.


People from other scripting languages always think theirs is better because they have a built in function to do that and not PHP (I am looking at pythonistas right now :-)).

In fact, it does exist, but few people know it. Meet pathinfo():

$ext = pathinfo($filename, PATHINFO_EXTENSION);

This is fast, efficient, reliable and built-in. pathinfo() can give you other information, such as canonical path, depending on the constant you pass to it.