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

前端之家收集整理的这篇文章主要介绍了php – 查找具有任何扩展名的特定名称的文件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
请注意,我希望隔间号码更改.
  1. <?PHP
  2. $compartment = "1";
  3.  
  4. /* HERE I NEED SOME SCRIPT TO FIND THE EXTENSION OF THE FILE NAME $compartment AND TO SAVE THAT AS A VARIABLE NAMED 'EXTENSION'.*/
  5.  
  6. if (file_exists($compartment.$extension)) {
  7. echo "$compartment.$extension exists!
  8. } else {
  9. echo "No file name exists that is called $compartment. Regardless of extension."
  10. }
  11. ?>
  12.  
  13.  
  14. <?PHP
  15. $compartment = "2";
  16.  
  17. /* HERE I NEED SOME SCRIPT TO FIND THE EXTENSION OF THE FILE NAME $compartment AND TO SAVE THAT AS A VARIABLE NAMED 'EXTENSION'.*/
  18.  
  19. if (file_exists($$compartment.$extension)) {
  20. echo "$compartment.$extension exists!
  21. } else {
  22. echo "No file name exists that is called $compartment. Regardless of extension."
  23. }
  24. ?>

谢谢!

你需要 glob().
  1. $compartment = "2";
  2.  
  3. $files = glob("/path/to/files/$compartment.*"); // Will find 2.txt,2.PHP,2.gif
  4.  
  5. // Process through each file in the list
  6. // and output its extension
  7. if (count($files) > 0)
  8. foreach ($files as $file)
  9. {
  10. $info = pathinfo($file);
  11. echo "File found: extension ".$info["extension"]."<br>";
  12. }
  13. else
  14. echo "No file name exists called $compartment. Regardless of extension."

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

  1. $compartments = array(1,3,6,9); // or whichever compartments
  2. // you wish to run through
  3.  
  4. foreach ($compartments as $compartment)
  5. {
  6. ..... insert code here .......
  7. }

猜你在找的PHP相关文章