查找具有任何扩展名的特定名称的文件

And*_*man 8 php file-extension file-exists

请注意,我希望隔间号码更改.

<?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."
    }
?>
Run Code Online (Sandbox Code Playgroud)

谢谢!

Pek*_*ica 21

你需要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."
Run Code Online (Sandbox Code Playgroud)

顺便说一句,你上面所做的就是为一个循环而哭泣.不要重复你的代码块,但将其中一个包装成:

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

 foreach ($compartments as $compartment)
  {
   ..... insert code here .......
  }
Run Code Online (Sandbox Code Playgroud)


Gor*_*don 5

抬头:

\n\n
    \n
  • glob \xe2\x80\x94 查找与模式匹配的路径名
  • \n
  • fnmatch \xe2\x80\x94 根据模式匹配文件名
  • \n
  • pathinfo \xe2\x80\x94 返回有关文件路径的信息
  • \n
\n