Home >Backend Development >PHP Problem >What are the three ways to get the file extension in php
Obtaining method: 1. Use the "array_pop(explode('.', file name))" statement; 2. Use the "pathinfo (file name) ['extension']" statement; 3. Use "strrev (strchr(strrev(filename),'.',true))" statement.
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
php gets the file suffix Name method 1:
<?php function getExt1($filename) { $arr = explode('.',$filename); return array_pop($arr); } $str="dir/upload.image.jpg"; echo getExt1($str); ?>
Output:
jpg
Description:
explode() function uses a string split Another string and returns an array of strings.
array_pop() function deletes the last element in the array.
php method 2 to get the file suffix name:
<?php function getExt4($filename) { $arr = pathinfo($filename); $ext = $arr['extension']; return $ext; } $str="dir/upload.image.jpg"; echo getExt4($str); ?>
Output:
jpg
Description:
pathinfo() function returns information about the file path in the form of an array.
The returned array elements are as follows:
[dirname]: directory path
[basename]: file name
[extension]: File suffix name
[filename]: File name without suffix
php method 3 to get the file suffix name:
<?php function getExt5($filename) { $str = strrev($filename); return strrev(strchr($str,'.',true)); } $str="dir/upload.image.jpg"; echo getExt5($str); ?>
Output:
jpg
Description:
strrev() function reverses a string.
strchr() function searches for the first occurrence of a string in another string. Syntax:
strchr(string,search,before_search);
Parameter | Description |
---|---|
string | Required. Specifies the string to be searched for. |
search | Required. Specifies the string to search for. If the argument is a number, searches for characters that match the ASCII value for that number. |
before_search | Optional. A Boolean value with a default value of "false". If set to "true", it will return the portion of the string preceding the first occurrence of the search parameter. |
Return value: Returns the rest of the string (from the matching point). Returns FALSE if the searched string is not found.
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of What are the three ways to get the file extension in php. For more information, please follow other related articles on the PHP Chinese website!