PHP uses the Glob function to traverse files and directories to explain _php tips

Source: Internet
Author: User

The PHP glob () function returns the file name or directory that matches the specified pattern. So we can use the Glob function to find the file, or we can implement the directory traversal.

Function Description: Array glob (string $pattern [, int $flags])

Function: Find a file path that matches the pattern, and return an array containing matching files (note: The file being checked must be a server system and cannot be used for remote files)

Parameter description: First parameter: match mode; Second Optional parameter:

    1. Glob_mark-Add a slash to each returned item
    2. Glob_nosort-Returns (not sorted) according to the original order in which the files appear in the directory
    3. Glob_nocheck-Returns the pattern for searching if no file match
    4. Glob_noescape-Backslash does not escape meta characters
    5. Glob_brace-expand {a,b,c} to match ' A ', ' B ' or ' C '
    6. Glob_onlydir-Returns only directory entries that match the pattern

Instance one: Gets all the files and subdirectories under the specified directory

<?php
   $directories = Glob ("/tmp/*", glob_onlydir);//Get all directories under the/tmp/directory
   $complete = glob ("/tmp/*");/Get/tmp/ All directories and files under the directory
   $files = Array_diff ($directories, $complete);//Get all Files under/tmp/directory

   echo "directories in/tmp/<br > ";
   foreach ($directories as $val) {
     echo "$val <br>\n";
   }
   echo "<br>files in/tmp/<br>";
   foreach ($files as $val) {
     echo "$val <br>\n";
   }
? >
 

Example two: You are still using Opendir readdir traverse file, you really out!

<?php
$files = Glob ("dir/*.jpg");
foreach ($files as $jpg) {
  echo $jpg, "\ n";
}
? >



The above is to PHP using the Glob function to traverse files and directories of data collation, follow-up continue to supplement the relevant information, thank you for your support of this site!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.