Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php "glob" pattern help

Tags:

html

php

xml

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


1 Answers

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/

like image 103
salathe Avatar answered Aug 09 '26 03:08

salathe