PHP获取文件的扩展名
一、使用pathinfo()函数:
1 <?php 2 /** 3 * 获取文件扩展名 4 * 5 * @param string $path 文件路径 6 * @return string 7 */ 8 function getExtByPathinfo($path) { 9 return pathinfo($path, PATHINFO_EXTENSION); 10 } 11 $path = "C:/Users/Yun/Downloads/ace-master.zip"; 12 print_r(getExtByPathinfo($path));
1 <?php 2 /** 3 * 获取文件扩展名 4 * 5 * @param string $path 文件路径 6 * @return string 7 */ 8 function getExtByPathinfo($path) { 9 $info = pathinfo($path); 10 return $info['extension']; 11 } 12 $path = "C:/Users/Yun/Downloads/ace-master.zip"; 13 print_r(getExtByPathinfo($path));
二、使用preg_split()函数:
1 <?php 2 /** 3 * 获取文件扩展名 4 * 5 * @param string $directory 文件路径 6 * @return string 7 */ 8 function getExtName($directory) { 9 // `preg_split()`:通过一个正则表达式分隔字符串 10 $arr = preg_split('/[\\.]/', $directory); 11 return $arr[count($arr) - 1]; 12 } 13 $directory = "C:/Users/Yun/Downloads/ace-master.zip"; 14 print_r(getExtName($directory));
三、使用end()函数:
1 <?php 2 /** 3 * 获取文件扩展名 4 * 5 * @param string $directory 文件路径 6 * @return string 7 */ 8 function getExtName($directory) { 9 $arr = explode('.', $directory); 10 11 // `end()`:将 array 的内部指针移动到最后一个单元并返回其值 12 return end($arr); 13 } 14 $directory = "C:/Users/Yun/Downloads/ace-master.zip"; 15 print_r(getExtName($directory));
四、使用strrchr()函数:
1 <?php 2 /** 3 * 获取文件扩展名 4 * 5 * @param string $directory 文件路径 6 * @return string 7 */ 8 function getExtName($directory) { 9 // `strrchr()`:查找指定字符在字符串中的最后一次出现 10 return substr(strrchr($directory, '.'), 1); 11 } 12 $directory = "C:/Users/Yun/Downloads/ace-master.zip"; 13 print_r(getExtName($directory));
五、使用strrpos()函数:
1 <?php 2 /** 3 * 获取文件扩展名 4 * 5 * @param string $directory 文件路径 6 * @return string 7 */ 8 function getExtName($directory) { 9 // `strrpos()`:计算指定字符串在目标字符串中最后一次出现的位置 10 return substr($directory, strrpos($directory, '.') + 1); 11 } 12 $directory = "C:/Users/Yun/Downloads/ace-master.zip"; 13 print_r(getExtName($directory));
六、使用preg_replace()函数:
1 <?php 2 /** 3 * 获取文件扩展名 4 * 5 * @param string $directory 文件路径 6 * @return string 7 */ 8 function getExtName($directory) { 9 // `preg_replace()`:执行一个正则表达式的搜索和替换 10 return preg_replace('/^.*\.([^.]+)$/D', '$1', $directory); 11 } 12 $directory = "C:/Users/Yun/Downloads/ace-master.zip"; 13 print_r(getExtName($directory));
七、使用SplFileInfo()类:
1 <?php 2 /** 3 * 获取文件扩展名 4 * 5 * @param string $directory 文件路径 6 * @return string 7 */ 8 function getExtName($directory) { 9 $file = new SplFileInfo($directory); 10 return $file->getExtension(); 11 } 12 $directory = "C:/Users/Yun/Downloads/ace-master.zip"; 13 print_r(getExtName($directory));