Following is a simple snippet I use to get a file extension in php, notice that the strrpos function returns the last position of the string “.” in filename in case there are multiple dots in file name.
- <?php
- /**
- * Function that returns file extension by its name.
- * @param unknown_type $fileName
- * @return $ext
- */
- function fileExt($fileName)
- {
- /* sttrpos to get last position of "." */
- $dot = strrpos($fileName, '.');
- if($dot === FALSE)
- return FALSE;
- $ext = substr($fileName, $dot+1);
- return $ext;
- }
- $fileName = "yangqi.us.txt";
- echo fileExt($fileName);
- ?>
<?php
/**
* Function that returns file extension by its name.
* @param unknown_type $fileName
* @return $ext
*/
function fileExt($fileName)
{
/* sttrpos to get last position of "." */
$dot = strrpos($fileName, '.');
if($dot === FALSE)
return FALSE;
$ext = substr($fileName, $dot+1);
return $ext;
}
$fileName = "yangqi.us.txt";
echo fileExt($fileName);
?>After doing some research, I found an easier way to utilize the php function “pathinfo()“. The function returns an array containing information about dirname, basename, extension and filename of a given path string or a filename. The sample code is as follow:
- <?php
- /**
- * Function that returns file extension by its name.
- * @param unknown_type $fileName
- * @return $ext
- */
- function fileExt($fileName)
- {
- $ext = pathinfo($fileName, PATHINFO_EXTENSION);
- return $ext;
- }
- $fileName = "yangqi.us.txt";
- echo fileExt($fileName);
- ?>
<?php
/**
* Function that returns file extension by its name.
* @param unknown_type $fileName
* @return $ext
*/
function fileExt($fileName)
{
$ext = pathinfo($fileName, PATHINFO_EXTENSION);
return $ext;
}
$fileName = "yangqi.us.txt";
echo fileExt($fileName);
?>