Home >Backend Development >PHP Problem >What are the 5 ways to get file extension in php
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.
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('.',$filename); return array_pop($arr); } $str="dir/upload.image.jpg"; echo getExt1($str); ?>
Output:
jpg
Method 2:
<?php function getExt2($filename) { $ext = strrchr($filename,'.'); return $ext; } $str="dir/upload.image.jpg"; echo getExt2($str); ?>
Output:
.jpg
Method 3:
<?php function getExt3($filename) { $pos = strrpos($filename, '.'); $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['extension']; 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,'.',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!