从图像文件名php中删除扩展名


remove extension from image filename php

我正在使用以下php代码将一个图像文件夹加载到html页面中。

我遇到的问题是,为了用作图像标题而引入的文件名显示了文件扩展名。

代码中提取名称的部分是title="$img"

如何删除文件扩展名?

<?php
$string =array();
$filePath='images/schools/';  
$dir = opendir($filePath);
while ($file = readdir($dir)) { 
    if (eregi("'.png",$file) || eregi("'.jpeg",$file) || eregi("'.gif",$file) || eregi("'.jpg",$file) ) { 
        $string[] = $file;
    }
}
while (sizeof($string) != 0) {
    $img = array_pop($string);
    echo "<img src='$filePath$img' title='$img' />";
}

?>

您可以使用pathinfo获得不带扩展名的文件名,因此对于title=",您可以使用pathinfo($file, PATHINFO_FILENAME);

$file_without_ext = substr($file, 0, strrpos(".", $file));

对于"最先进"的OO代码,我建议如下:

$files = array();
foreach (new FilesystemIterator('images/schools/') as $file) {
    switch (strtolower($file->getExtension())) {
        case 'gif':
        case 'jpg':
        case 'jpeg':
        case 'png':
            $files[] = $file;
            break;
    }
}
foreach ($files as $file) {
    echo '<img src="' . htmlentities($file->getPathname()) . '" ' .
         'title="' . htmlentities($file->getBasename('.' . $file->getExtension())) . '" />';
}

优点:

  • 您不再使用不推荐使用的ereg()函数
  • 您可以使用htmlentities()转义可能的特殊HTML字符

您可以使用substr来去除文件扩展名,如下所示:

$fileName =  $request->file->getClientOriginalName();
$file_without_ext = substr($fileName, 0, strrpos($fileName,"."));