开发者

PHP Determining a file based on parameters in regular expression

I'm开发者_如何学C 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


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
    )
)


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?


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;


glob('C:/Users/programmer/Downloads/reviews/*/p*.html');
glob('C:/Users/programmer/Downloads/reviews/*/r*.html');
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜