Home >Backend Development >PHP Tutorial >How to get the file extension in PHP_PHP Tutorial
There are many ways to get the suffix of a file. Let’s introduce one below.
<?php $file_name = "bkjia.txt"; echo get_exname($file_name); /** * 获取文件扩展名 * @param unknown_type $file_name * @return $ex_name */ function get_exname($file_name) { if(empty($file_name)) return false; $file_name = strtolower($file_name); $rev_str = strrev($file_name); $ex_name_len = strpos($rev_str,'.'); //扩展名的长度 $file_name_len = strlen($file_name); $ex_name = substr($file_name, $file_name_len - $ex_name_len); return $ex_name; } ?>
strtolower() function converts a string to lowercase.
strrev() function reverses a string.
The strpos() function returns the position of the first occurrence of a string in another string.
It is to first find the position of the symbol '.', and then calculate the length of the extension. Then use the total length of the string minus the length of the extension to calculate the length that needs to be intercepted.