Search code examples
phpglob

Prevent glob from selecting a file with a specific file name


I have a folder with 5 html files. The files are called:

  • page-1.html
  • page-2.html
  • page-hello.html
  • page-32.html
  • yo-page-text.html

I wish to use glob function to return an array with only the files formatted: "page[number 0 - 1000]". So essentially I wish the glob function to return the following pages from the example above:

  • page-1.html
  • page-2.html
  • page-32.html

This is the code that I have managed to write so far:

<?php
    $directory = "testfolder/";
    foreach (glob($directory . "page-*.html") as $filename) {
        echo basename($filename);
    }
?>

Solution

  • The glob pattern is not as flexible as RegEx, so unless someone has some other magic, you can filter after the glob:

    $files = preg_grep('/page-[0-9]+\.html/', glob($directory . '*.*'));
    

    If the glob pattern supported repetition + then it would be easy. Bash and Korn shells offer it with +([0-9]) but PHP doesn't.

    You could also check for one number and trust that what follows matched by * will be numbers with: glob($directory . 'page-[0-9]*.html'), but this could match page-0-hello.html as well.