I use these regular expressions all the time, but it’s much more convenient to have them both in convenient PHP functions.
file_ext()
Returns only the file extension (without the period).
function file_ext($filename) {
return preg_replace('/^.*\./', '', $filename);
}
file_ext_strip()
Returns the file name, less the extension.
function file_ext_strip($filename){
return preg_replace('/\.[^.]*$/', '', $filename);
}
I test it using the regex pal and the result of the first function does’t work so well.
http://regexpal.com/?flags=®ex=(^.*.)&input=igor.escobar.jpg
@Igor Escobar: Sorry! You were right, there was an escape issue so the backslashes weren’t appearing in the regex pattern. They work now :)
Very handy, and much more elegant than the ‘traditional’ explode() / strstr() / substr() etc. methods.
Of course, you could also just use PHP’s built-in functions for this:
<?php
function file_ext ($name)
{
$info = pathinfo($name);
return $info['extension'];
}
function file_ext_strip ($name)
{
$info = pathinfo($name);
return $info['filename'];
}
# DEMO
$filename = "/path/to/some.file";
echo file_ext($filename).’<br>’;
echo file_ext_strip($filename).’<br>’;
?>