tags:

views:

60

answers:

2

I have a directory with sitemaps, which all end with a number.

I have an automatic sitemap generator script which needs to count all sitemaps in a folder using glob.

Currently I am stuck here.

What I need is to count all sitemap files which has a number in them, so I don't count the ones without any numbers.

For instance, in my root I have a sitemap.xml file, then I also have sitemap1.xml, sitemap2.xml, sitemap3.xml etc...

I need to use glob to only return true when the filename contains a number like "sitemap1.xml".

Is this possible?

$nr_of_sitemaps = count(glob(Sitemaps which contains numbers in their filenames)); 

Thanks

+2  A: 

To glob for files ending in <digit>.xml you can use a pattern like:

*[0-9].xml

So to count the matches, the PHP might look like:

$count = count(glob('/path/to/files/*[0-9].xml'));

If you want super-fine control (moreso than glob can give) over the matching files, you could use a general pattern then use preg_grep to filter the resulting array to precisely what you want.

$count = count(
    preg_grep(
        '#(?:^|/)sitemap\d{1,3}\.xml$#',
        glob('/path/to/files/sitemap*.xml')
    )
);

See also: http://cowburn.info/2010/04/30/glob-patterns/

salathe
So in my case: glob('sitemap[0-9].xml') ? This must work even if there are several digits, like "sitemap43.xml".
Camran
No, `[0-9]` will only match a single digit. If you want to cater for variable numbers of digits, go with my regex suggestion or perhaps `sitemap*[0-9].xml` if false positives won't also match that.
salathe
+1 for preg_grep. Very useful and very much underrated function.
stereofrog
A: 

Must you use glob? It's trivial to just use the more powerful regex engine instead:

if ($handle = opendir('/your/path')) {

    while ( ($filename = readdir($handle)) !== false ) {
        if (preg_match('/sitemap\d+\.xml/', $filename)) {
            // got one!
        }
    }

    closedir($handle);
}
webbiedave