请注意,我想要更改车厢号码。

<?php
    $compartment = "1";

        /* HERE I NEED SOME SCRIPT TO FIND THE EXTENSION OF THE FILE NAME $compartment AND TO SAVE THAT AS A VARIABLE NAMED 'EXTENSION'.*/

    if (file_exists($compartment.$extension)) {
        echo "$compartment.$extension exists!
    } else {
        echo "No file name exists that is called $compartment. Regardless of extension."
    }
?>


<?php
    $compartment = "2";

        /* HERE I NEED SOME SCRIPT TO FIND THE EXTENSION OF THE FILE NAME $compartment AND TO SAVE THAT AS A VARIABLE NAMED 'EXTENSION'.*/

    if (file_exists($$compartment.$extension)) {
        echo "$compartment.$extension exists!
    } else {
        echo "No file name exists that is called $compartment. Regardless of extension."
    }
?>

谢谢你!


你需要glob()

$compartment = "2";

$files = glob("/path/to/files/$compartment.*"); // Will find 2.txt, 2.php, 2.gif

// Process through each file in the list
// and output its extension
if (count($files) > 0)
foreach ($files as $file)
 {
    $info = pathinfo($file);
    echo "File found: extension ".$info["extension"]."<br>";
 }
 else
  echo "No file name exists called $compartment. Regardless of extension."

顺便说一句,你上面所做的事情是在等待循环。不要重复您的代码块,但将其中之一包装到此中:

 $compartments = array(1, 3, 6, 9); // or whichever compartments 
                                    // you wish to run through

 foreach ($compartments as $compartment)
  {
   ..... insert code here .......
  }

抬头:

  • glob — 查找与模式匹配的路径名
  • fnmatch — 将文件名与模式匹配
  • pathinfo — 返回有关文件路径的信息

如果不止一个怎么办?不管怎样,你可以使用 glob。

你希望这个发现能起到什么作用?仅搜索 1 个特定文件夹还是从特定文件夹开始搜索所有文件夹?部分匹配符合条件还是完整文件名应该匹配?无论如何,您可能想检查PHP 参考中的opendir和readdir函数

只有一个具有该名称的文件,因此我不必担心多个匹配。不应返回部分匹配项。即我想分别返回1和13。

谢谢。我需要在代码中多次引用“恢复”文件。这会是一个问题吗?

@Andy不,只要你在foreach $files as $file循环内做它。(您也可以在其外部使用该变量,但随后您必须选择哪个变量。)