Finding a file with a specific name with any extension

前端 未结 2 1087
抹茶落季
抹茶落季 2021-01-02 05:59

Please note that I want the compartment number to change.



        
相关标签:
2条回答
  • 2021-01-02 06:20

    You need 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."
    

    by the way, what you are doing above is crying for a loop. Don' repeat your code blocks, but wrap one of them into this:

     $compartments = array(1, 3, 6, 9); // or whichever compartments 
                                        // you wish to run through
    
     foreach ($compartments as $compartment)
      {
       ..... insert code here .......
      }
    
    0 讨论(0)
  • 2021-01-02 06:40

    Look up:

    • glob — Find pathnames matching a pattern
    • fnmatch — Match filename against a pattern
    • pathinfo — Returns information about a file path
    0 讨论(0)
提交回复
热议问题