Home >Backend Development >PHP Tutorial >Summary of how to get file extension in PHP

Summary of how to get file extension in PHP

php中世界最好的语言
php中世界最好的语言Original
2018-05-16 13:42:521654browse

This time I will bring you a summary of how PHP obtains file extensions. What are the precautions for PHP to obtain file extensions? The following is a practical case, let's take a look.

This is a written test question I encountered when applying for an internship:

Use more than five methods to obtain the extension of a file.

Requirements: dir/upload.image.jpg, find .jpg or jpg,

Must use PHP's own processing function for processing, the method cannot be obviously repeated, and can be encapsulated into a function, For example, get_ext1($file_name), get_ext2($file_name)

The following are five methods I summarized by referring to online information. They are all relatively simple and do not say much. Say, go directly to the code:

Method 1:

function getExt1($filename)
{
   $arr = explode('.',$filename);
   return array_pop($arr);;
}

Method 2:

function getExt2($filename)
{
   $ext = strrchr($filename,'.');
   return $ext;
}

Method 3:

function getExt3($filename)
{
   $pos = strrpos($filename, '.');
   $ext = substr($filename, $pos);
   return $ext;
}

Method 4:

function getExt4($filename)
{
   $arr = pathinfo($filename);
   $ext = $arr['extension'];
   return $ext;
}

Method 5:

function getExt5($filename)
{
   $str = strrev($filename);
   return strrev(strchr($str,'.',true));
}

I believe you have mastered it after reading the case in this article For more exciting methods, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Detailed explanation of the steps for PHP to use file_get_contents to send http requests

PHP implements random elimination algorithm

The above is the detailed content of Summary of how to get file extension in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn