【问题标题】:How can I check only file name not extension is exists如何仅检查文件名而不是扩展名是否存在
【发布时间】:2016-02-23 09:21:31
【问题描述】:

我怎样才能只检查文件名而不是像jpeg, jpg, doc, xls 这样的扩展名。然后复制其完整名称,如example.jpegexample.doc

如果可能的话,我们可以像这样存储它的上两个父目录

如果exam​​ple.jpeg存储在

main_dir/second_dir/example.jpeg 

所以我想将此路径存储在 php 变量中。

我知道我可以使用glob()

$result = glob ("./uploads/filename.*");

并检查$result 值。

但我想存储完整的文件名和可能的两个父目录路径。

下面是我的代码

$filename = '/www/test1/'. $file . '*' ;
if (count(glob($filename)) > 0) {
    echo "The file $filename exists";
} else {
    echo "The file $filename does not exist";
}

编辑

根据 luweiqi 解决方案更新查询

foreach(glob("/uploads/".$productnumber."/". $productnumber."b.*", GLOB_NOSORT) as $file) {  
        echo "Filename: " . $file . "<br />";      
        $image2 = "/uploads/".$productnumber."/".$file;
    }  

图像的最后一个字母从 a 到 f 变化。所以你能做一些更正吗? 我想检查图片是否存在于 uploads/productnumber/productnumber (a/b/c/d/e/f).jpg 或 png 或 jpeg 等上,并将该文件名存储在 php 变量中。

【问题讨论】:

  • 那么真正的问题是:What have you tried?
  • 嗨,鸣人,正在等待这个问题。请检查更新问题。

标签: php


【解决方案1】:

你可以使用file_exists()函数。

$pngFile = '/path/to/foo.png';
$docFile = '/path/to/foo.doc';
// Returns TRUE if the file or directory specified by filename exists; FALSE otherwise.
if (file_exists($filename) || file_exists($docFile)) {
    echo "The file $filename exists";
} else {
    echo "The file $filename does not exist";
}

使用glob函数

$files=[];
$result = glob ("/path/to/foo.*");  
foreach ($result as $file) { 
     echo "$file size " . filesize($file) . "\n";       
     $files[] = $file; 
} 
echo '<pre>'; print_r($files);

【讨论】:

  • 嗨拉维,我已经更新了我的问题。你能检查一次吗?
【解决方案2】:

你可以使用:

<?php

    foreach(glob("../directory/*{a,b,c,e,f}.*", GLOB_BRACE) as $file) {
        echo "Filename: " . $file . "<br />";
    }
?>

此代码将获取文件名并回显它,如果您想将其分配给变量,可以相应地更改它。

【讨论】:

  • 让我试试这个.. 我可以在路径中使用 php 变量使用适当的连接,如。我的目录结构基于 product_no。
  • @John 我不明白你的上下文,也许在你的问题中详细说明你想要达到的目标,谢谢
  • foreach(glob("/uploads/".$productnumber."/".$productnumber."b.*", GLOB_NOSORT) as $file) { echo "Filename:" . $文件。 "
    "; $image2 = "/uploads/".$productnumber."/".$file;图像的最后一个字母变化如 a 到 f 。所以你能做一些更正吗?我想检查图片是否存在于 uploads/productnumber/productnumber(lastletter like a b c).jpg/png 等,并将该文件名存储在 php 变量中。
猜你喜欢
  • 2020-03-30
  • 1970-01-01
  • 1970-01-01
  • 2011-01-14
  • 2013-05-24
  • 1970-01-01
  • 2011-03-19
  • 2012-08-21
  • 2015-09-05
相关资源
最近更新 更多