使用五种以上方式获取一个文件的扩展名 2016.6.1

来源:互联网 发布:java hash算法原理 编辑:程序博客网 时间:2024/06/16 16:21

在PHP面试中,经常碰到此题:要求写出5种以上的方法,获取一个文件的扩展名,其实也是在考察面试者基础知识的掌握程度,下面整理了几种常用的方法(下面方法返回的都是不带’.'的,如果要求带‘.’的话 自己改一下):

<?php
 
 $file = ‘siyuantlw/程序设计.php’;
 
 function getExt1($file) {
  returnsubstr(strrchr($file,’.'),1);
 }
 function getExt2($file) {
  returnsubstr($file,strrpos($file,’.')+1);
 }
 function getExt3($file) {
  returnstrrev(substr(strrev($file),0,strpos(strrev($file),’.')));
 }
 function getExt4($file) {
  return array_pop(explode(‘.’,$file)); //array_pop介绍
 }
 function getExt5($file) {
  $arr = pathinfo($file);
  return $arr['extension'];
  //或者写成下面这种
  //returnpathinfo($file,PATHINFO_EXTENSION);
 }
 function getExt6($file) {
  $temp = strtok($file, ‘.’); //strtok函数说明
    while($temp !== false ){
        $file_extension = $temp;
        $temp = strtok(‘.’);
    }
    return $file_extension;
 }

function getExt7($file) {
  while($dot = strpos($file,“.”))
  {
   $file =substr($file, $dot+1);
  }
  return $file;
 }
 echo getExt1($file).’<br/>’;
 echo getExt2($file).’<br/>’;
 echo getExt3($file).’<br/>’;
 echo getExt4($file).’<br/>’;
 echo getExt5($file).’<br/>’;
 echo getExt6($file).’<br/>’;

echo getExt7($file).’<br />’;

0 0