简体   繁体   English

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

[英]remove extension from image filename php

I am loading a folder of images into a html page using the following php code.我正在使用以下 php 代码将图像文件夹加载到 html 页面中。

The problem I am having is that the file name which is being brought through in order to be used as the image caption is showing the file extension.我遇到的问题是,为了用作图像标题而被引入的文件名显示了文件扩展名。

The part of the code where the name is being pulled is the title='$img'名称被拉取的代码部分是 title='$img'

How do I get it to remove the file extension?我如何让它删除文件扩展名?

<?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));

For a "state-of-the-art" OO code, I suggest the following:对于“最先进的”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())) . '" />';
}

Benefits:好处:

  • You do not use the deprecated ereg() functions anymore.您不再使用已弃用的ereg()函数。
  • You escape possible special HTML characters using htmlentities() .您可以使用htmlentities()转义可能的特殊 HTML 字符。

you can get rid of file extention with substr, like this:您可以使用 substr 摆脱文件扩展名,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM