摘要:在PHP面试中,经常碰到此题 :要求写出5种以上的方法,获取一个文件的扩展名,其实也是在考察面试者基础知识的掌握程度,下面整理了几种常用的方法(下面方法返回的都是不带’.'的,如果要求带 ‘.’的话 自己改一下):<?php $file = ‘siyuantlw/程序设计.php’; function
在PHP面试中,经常碰到此题 :要求写出5种以上的方法,获取一个文件的扩展名,其实也是在考察面试者基础知识的掌握程度,下面整理了几种常用的方法(下面方法返回的都是不带’.'的,如果要求带 ‘.’的话 自己改一下):
<?php $file = ‘siyuantlw/程序设计.php’; function getExt1($file) { return substr(strrchr($file,’.'),1); } function getExt2($file) { return substr($file,strrpos($file,’.')+1); } function getExt3($file) { return strrev(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']; //或者写成下面这种 //return pathinfo($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 />’;