查找给定文件名的文件扩展名


Find the file extension of the given file name

如何查找给定文件名的扩展名:

请参阅下面的代码:

$file_name = "sample.jpg";

Output will be: .jpg

我需要找到文件名的扩展名

示例:如果我们解析样本.jpg我应该返回.jpg

这里有一种方法可以找到:

<?php
$filename = "sample.txt.jpg";
$ext = substr($filename, strrpos($filename, "."));
echo $ext;
?>
你可以

尝试使用爆炸

    $file_name = "sample.jpg";
    $pieces = explode(".", $file_name);
    echo $pieces[0]; // sample
    echo '.'.$pieces[count($pieces)-1]; // .jpg

你也可以使用它:

$ext = pathinfo($file_name, PATHINFO_EXTENSION);
echo $ext;//jpg

使用 PHP SPL 类查找有关文件的任何信息。 更多细节阅读 这里

$file = new SplFileInfo($path);
$ext  = $file->getExtension();