[英]How to select files in directory that match a specific name filter? — php
我试图建立一个数据库更新脚本,该脚本从应用程序实际运行的下一个版本开始执行mysqldumps。 当数据库中有一些更改时,我将这些转储放在一个文件夹中。 以下脚本工作可以完成此工作,但是如果我将过滤器设置为当前<版本以下,它将显示正确的文件;如果我将过滤器设置为在当前版本之上(>),则将显示正确的文件PLUS schema_backup.sql,并且不应该。 在我的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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.