Home >Backend Development >PHP Problem >What are the 5 ways to get file extension in php

What are the 5 ways to get file extension in php

青灯夜游
青灯夜游Original
2021-06-30 19:03:335267browse

Method: 1. Use the explode and array_pop functions; 2. Use the strrchr function; 3. Use the substr and strrpos functions; 4. "pathinfo (file) ['extension']" statement; 5. Use strrev, strchr and strrev functions.

What are the 5 ways to get file extension in php

The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer

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

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

must use PHP The built-in processing function is used for processing. The method cannot be obviously repeated and can be encapsulated into functions, such as get_ext1($file_name), get_ext2($file_name)

The following is The five methods I summarized by referring to online information are relatively simple. Without further ado, let’s go directly to the code:

Method 1:

<?php
function getExt1($filename)
{
         $arr = explode(&#39;.&#39;,$filename);
         return array_pop($arr);
}
$str="dir/upload.image.jpg";
echo getExt1($str);
?>

Output:

jpg

Method 2:

<?php
function getExt2($filename)
{
         $ext = strrchr($filename,&#39;.&#39;);
         return $ext;
}
$str="dir/upload.image.jpg";
echo getExt2($str);
?>

Output:

.jpg

Method 3:

<?php
function getExt3($filename)
{
         $pos = strrpos($filename, &#39;.&#39;);
         $ext = substr($filename, $pos);
         return $ext;
}
$str="dir/upload.image.jpg";
echo getExt3($str);
?>

Output:

.jpg

Method 4:

<?php
function getExt4($filename)
{
         $arr = pathinfo($filename);
         $ext = $arr[&#39;extension&#39;];
         return $ext;
}
$str="dir/upload.image.jpg";
echo getExt4($str);
?>

Output:

jpg

Method 5:

<?php
function getExt5($filename)
{
         $str = strrev($filename);
         return strrev(strchr($str,&#39;.&#39;,true));
}
$str="dir/upload.image.jpg";
echo getExt5($str);
?>

Output:

jpg

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of What are the 5 ways 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