tags:

views:

37

answers:

4

I'm trying to determine a file based on specific parameters. First, I am recursively iterating through a directory structure such as the following:

  • C:/Users/programmer/Downloads/reviews/XBOX
  • C:/Users/programmer/Downloads/reviews/PS3
  • C:/Users/programmer/Downloads/reviews/GBA

Please notice the console game type at the end of the string. Following this, we have the following:

  • C:/Users/programmer/Downloads/reviews/XBOX/p123.html
  • C:/Users/programmer/Downloads/reviews/XBOX/r123.html

If you notice in the second section, there is one file that has a p and one that has an r.

My end goal is to determine which files are p* and which are r*, so my regular expression I'd like to be something of the following (pseudo-code)

/console/p*/

or

/console/r*/

In summary, I need to iterate through the files and know at the end of my function the filename AND the filetype (p or r) without caring about the console type. Thanks for the help

A: 

like

 preg_match('~/([pr])[^/]+$~', $file, $m);
 if($m[1] == 'p') something
 if($m[1] == 'r') something else

// edit: although this answers your question directly, this is not the most effective way. Depending upon what you want, you're better off using glob(), as other people suggested, or glob() + preg_grep() or, even better, a database instead of files. Can you tell us more about what're trying to achieve?

stereofrog
A: 

Assuming you just want to get lists of files, distinguished by the first letter of their filename:

Walk the directory tree, get the filename into a variable like $filename.

$files[$filename[0]][] = $filename;

timdev
A: 
glob('C:/Users/programmer/Downloads/reviews/*/p*.html');
glob('C:/Users/programmer/Downloads/reviews/*/r*.html');
powtac
+1 for simplicity
Frank Farmer
glob is a great suggestion but it's not going to fit with the scheme of what I was trying to accomplish
Jonathan Kushner
+2  A: 

The PHP glob function will walk through a directory matching all files that meet a given criteria.

$files = array();

foreach(glob("C:/Users/programmer/Downloads/reviews/*/p*.html") as $filename) {
    $files['p'][] = $filename;
}

foreach(glob("C:/Users/programmer/Downloads/reviews/*/r*.html") as $filename) {
    $files['r'][] = $filename;
}

This will give you an array looking like this:

array (
    p =>  array (
        0 => p123.htm
        1 => p456.htm
    )

    r => array (
        0 => r123.htm
        1 => r456.htm
    )
)
RMcLeod
There's no need to iterate through the results, is there? Wouldn't this work just as well?: $files['p'] = glob("C:/Users/programmer/Downloads/reviews/*/p*.html"); ...in fact, glob sometimes returns false, which would cause your foreach loops to error out.
Frank Farmer