Get File Extension
Very handy PHP function to get the file extension of a file name like something.jpg
Method 1: (best way)
1 2 3 4 5 6 7 8 9 10 11 | // get_file_extension ( string [the file name] , boolean [lower case] ) function get_file_extension($str,$low = true){ $i = strrpos($str,'.'); if (!$i) return ''; $l = strlen($str) - $i; $ext = substr($str,$i+1,$l); if($low == true) $ext = strtolower($ext); return $ext; } |
Method 2:
1 2 3 4 5 6 7 8 9 10 | // get_file_extension ( string [the file name] , boolean [lower case] ) function get_file_extension($str,$low = true){ $ar = explode('.',$str); if(empty($ar)) return ''; $ar = array_reverse($ar); if($low == true) $ext = strtolower($ar[0]); return $ext; } |
Both functions produce the same output but one uses the string functions and the other uses array function. If you think about it, to manipulate and create arrays take more memory then manipulating regular text. (internally arrays are created using those same string manipulation methods) So method one is better because it uses most simple way to get what you need.