RegEx pattern in glob function

后端 未结 1 732
我在风中等你
我在风中等你 2021-02-08 22:41

I recive a filename in a function. I want to return all files similar to this file (by filename) from other directory. I wrote this:

    $thumbDir = $this->fi         


        
1条回答
  •  [愿得一人]
    2021-02-08 23:00

    glob() is really a quasi-regex engine. From a comment on the docs, it allows a ? and a *:

    glob uses two special symbols that act like sort of a blend between a meta-character and a quantifier. These two characters are the * and ?

    The ? matches 1 of any character except a /

    The * matches 0 or more of any character except a /

    If it helps, think of the * as the pcre equivalent of .* and ? as the pcre equivalent of the dot (.)

    This means you can't use your expression _[0-9]+\x[0-9]+_thb. in glob(). Instead, you can look in the whole directory and see if it matches with preg_match():

    $glob = glob('/path/to/dir/*');
    foreach($glob as $file) {
        if(preg_match('/_\d+x\d+_thb\./', $file)) {
            // Valid match
            echo $file;
        }
    }
    

    Realize that in glob(/path/to/dir/*);, the * does not match a / so this will not get any files in subdirectories. It will only loop through every file and directory in that path; if you want to go deeper, you will have to make a recursive function.

    Note I cleaned your expression:

    _\d+x\d+_thb\.
    

    \d roughly equals [0-9] (it also includes Arabic digit characters, etc.), you do not need to escape x (so no \x), and you want to escape the period (\.).

    0 讨论(0)
提交回复
热议问题