如何在目录中选择与特定名称过滤器匹配的文件?——php


How to select files in directory that match a specific name filter? -- php

我试图建立一个数据库更新脚本,从应用程序实际运行的下一个版本开始执行mysqldumps。当数据库中有一些更改时,我将这些转储文件放在一个文件夹中。下面的脚本可以完成这项工作,但是如果我将过滤器设置在当前<版本,它显示正确的文件,如果我设置过滤器显示上面(>)的当前版本,它显示正确的+ schema_backup。SQL,这不应该。在我的sql文件夹我有:

  • 0.2.0.sql
  • 0.2.1.sql
  • 0.2.2.sql
  • 0.2.3.sql
  • schema_backup.sql
代码:

$current_version = '0.2.1'; 

$dir = "sql/";
// Open a directory, and read its contents
if (is_dir($dir)){
  if ($dh = opendir($dir)){
    while (($file = readdir($dh)) !== false){
    if (($file != '.') && ($file != '..') && ($file > $current_version . '.sql')) {
   echo "" . $file . "<br>";
      exec('mysql -h' . host . ' -u' . username . ' -p' . password . ' ' . database . ' < sql/' . $file . '.sql');
 }
 }
 closedir($dh);
  }
}

根据文件名的第一个字符删除错误的文件,并使用version_compare()执行比较:

foreach (glob("$dir/[0-9]*.sql") as $file) {
    if (version_compare($current_version, pathinfo($file, PATHINFO_FILENAME), '<')) {
        // load dump
    }
}

preg_match('/''d+''.''d+''.''d+''.sql/',$file)添加到if语句中。(可取消...检查)

if (preg_match('/''d+''.''d+''.''d+''.sql/',$file) && $file > $current_version.'.sql'))

正则表达式的组成部分是:

/ ... /     boundary of the expression
''d+        one or more digits (backslash must be double so preg "sees" 'd
''.         a literal period (again, double backslash to get one)
sql         the file extension