开发者

Listing directories in PHP where the name starts with a digit

开发者 https://www.devze.com 2023-01-06 00:46 出处:网络
The following code give me all the directories: print_r(glob(\'*\',GLOB_ONLYDIR)); But I need only the ones that start with a digit (version numbers 3.0.4, 3.0.5开发者_JAVA技巧 etc).

The following code give me all the directories:

print_r(glob('*',GLOB_ONLYDIR));

But I need only the ones that start with a digit (version numbers 3.0.4, 3.0.5开发者_JAVA技巧 etc).

I was thinking of using a foreach loop and some test conditions.

Is there another way to do this?


You can use simple regular-expression-like constructs:

print_r(glob("[0-9]*", GLOB_ONLYDIR));

Given these directories:

12test
1test
2test
test

The above glob returns:

Array
(
    [0] => 12test
    [1] => 1test
    [2] => 2test
)

You can narrow it down further if you like:

print_r(glob("[0-9]\.[0-9]\.[0-9]*", GLOB_ONLYDIR));

Given these directories:

3.0.4.Test
3.0.Test

The above glob returns:

Array
(
    [0] => 3.0.4.Test
)

You might find this useful:
Glob Patterns for File Matching in PHP


I would recommend checking out the directory interator in php rather than glob

http://php.net/manual/en/class.directoryiterator.php

<?php
$iterator = new DirectoryIterator(dirname(__FILE__));
foreach ($iterator as $fileinfo) {
    if ($fileinfo->isDir()) {
        // check if $fileinfo->getFilename() matches your criteria
    }
}
?>

As @Mike says, you can use the Regex Interator too. http://php.net/regexiterator


foreach(glob('*',GLOB_ONLYDIR) as $directoryname)
{
    if (strstr('0123456789',substr($directoryname,0,1))!="")
    {
         //$directoryname starts with a digit
    }
}


If you want to retrieve all directories that matches 3.0.4, or 3.0.5 or 3.0.10 , you can use the following code.

$dirs = glob("[0-9]+\.[0-9]+\.[0-9]+", GLOB_ONLYDIR);


Or by using a Regex Filter iterator, in case you need real regex power ('cos GLOB hasn't)

$dir_iterator = new DirectoryIterator('./');
$regex = '#^\d.*$'; // something really basic for now
$iterator = new RegexIterator($dir_iterator, $regex);

foreach ($iterator as $dir_object)
   {
   if ($dir_object->isDir())
       {
       // Just do something with it.
       echo $dir_object->getPathname()."<br/>\n"; 
       }
   }

I imagine it could be done a little bit shorter, and it could be enhanced. Anyway, glad to have learned a new approach towards directory filtering today ;)

0

精彩评论

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