php截取文件后缀的几种方法

$file = "test.php";
  • 方式1    explode()函数
 
  1. //字符串转换成数组

  2. $arr = explode('.',$file);

  3. echo $arr[count($arr)-1];

  • 方式2    strrpos()函数
 
  1. //最后一次出现位置

  2. echo substr($file, strrpos($file, '.')+1);

  • 方式3    strrchr()函数
 
  1. //最后一次出现的位置

  2. echo substr(strrchr($file,'.'),1);

  • 方式4    explode()函数    strrev()函数
 
  1. //将字符串倒叙切割为数组 再把数组下标为0的倒叙输出

  2. echo strrev(explode('.', strrev($file))[0]);

  • 方式5    end()函数
 
  1. //end()返回数组的最后一个元素

  2. $arr=explode('.', $file);

  3. echo end($arr);

  • 方式6    pathinfo()函数
 
  1. /*

  2. * 函数以数组的形式返回文件路径的信息

  3. *

  4. * 包括以下的数组元素:

  5. * [dirname]

  6. * [basename]

  7. * [extension]

  8. *

  9. * 可选。规定要返回的数组元素。默认是 all。

  10. * 可能的值:

  11. * PATHINFO_DIRNAME - 只返回 dirname

  12. * PATHINFO_BASENAME - 只返回 basename

  13. * PATHINFO_EXTENSION - 只返回 extension

  14. */

  15.  
  16. //两种方式都可以

  17. echo pathinfo($file, PATHINFO_EXTENSION);

  18.  
  19. echo pathinfo($file)['extension'];

  • 方式7    array_pop()函数
  1. $arr=explode('.', $file);

  2. echo array_pop($arr);

猜你喜欢

转载自blog.csdn.net/qq_41718455/article/details/81223080