Various Methods to Retrieve File Extension in PHP
This article demonstrates seven different PHP techniques for extracting a file's extension, including using substr with strrchr, substr with strrpos, explode with array indexing, end(), pathinfo, and PATHINFO_EXTENSION, providing code examples and brief explanations for each method.
This guide presents multiple ways to obtain a file's extension in PHP, offering concise code snippets and explanations for each approach.
Method 1:
$file = 'x.y.z.png';
echo substr(strrchr($file, '.'), 1);Explanation: strrchr($file, '.') finds the last occurrence of a dot and returns the substring from that point; substr(..., 1) removes the leading dot.
Method 2:
$file = 'x.y.z.png';
echo substr($file, strrpos($file, '.') + 1);Explanation: strrpos($file, '.') returns the position of the last dot, and substr extracts the characters after it.
Method 3:
$file = 'x.y.z.png';
$arr = explode('.', $file);
echo $arr[count($arr) - 1];Explanation: explode splits the filename by dots into an array; the last element (index count($arr)-1) is the extension.
Method 4:
$file = 'x.y.z.png';
$arr = explode('.', $file);
echo end($arr); // end() returns the last array elementExplanation: Similar to Method 3, but uses end() to fetch the final array element directly.
Method 5:
$file = 'x.y.z.png';
echo strrev(explode('.', strrev($file))[0]);Explanation: The filename is reversed, split by dot, the first part (original extension) is taken, then reversed back.
Method 6:
$file = 'x.y.z.png';
echo pathinfo($file)['extension'];Explanation: pathinfo() returns an associative array with file path details; the 'extension' key holds the file extension.
Method 7:
$file = 'x.y.z.png';
echo pathinfo($file, PATHINFO_EXTENSION);Explanation: Using the second argument of pathinfo(), PATHINFO_EXTENSION, directly returns the extension as a string.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
