使用正则表达式对文件列表进行排序
Using Regex to sort through a list of files
我正在编写一个脚本来对文件列表进行排序,获取与特定文件名匹配的最新文件,并将其复制到另一个文件夹。
我在 PHP 中写这篇文章,然后在每天的特定时间使用 CRON 将其设置为 运行。
文件的命名方式如下:
VS-订单-出口-105.xml
VS-订单-出口-104.xml
current-VS-order-export-105,xml
当前 VS 订单导出。104.xml
我需要获取最新的这些文件,格式为 'order-export-(number).xml'。那些前缀为 'current-' 的应该被忽略。
我似乎无法让 Regex 正确执行此操作。这是我得到的:
<?php $src = '/public_html/folder/exports/';
$files_src = scandir($src, SCANDIR_SORT_DESCENDING);
foreach($files_src as $file) {
if (preg_match('/(^VS-), (.*)/A', $file) && !is_dir($src . $file)) {
$newest_file_src = $files_src[1];
$newest_file_path_src = $src . $files_src[1];
$dest_file_path = '/public_html/orders/';
rename($newest_file_path_src, $dest_file_path);
}
} ?>
有人可以指出我做错了什么吗?
提前致谢!
在您的模式中,您试图匹配逗号后跟不存在的 space。
对于更具体的模式,您可以使用
\AVS-order-export-\d+\.xml\z
\A
字符串开头
VS-order-export-
字面匹配
\d+\.xml
匹配1+个数字和.xml
\z
字符串结束
例如
if (preg_match('/\AVS-order-export-\d+\.xml\z/', $file)) {
我正在编写一个脚本来对文件列表进行排序,获取与特定文件名匹配的最新文件,并将其复制到另一个文件夹。 我在 PHP 中写这篇文章,然后在每天的特定时间使用 CRON 将其设置为 运行。
文件的命名方式如下: VS-订单-出口-105.xml VS-订单-出口-104.xml current-VS-order-export-105,xml 当前 VS 订单导出。104.xml
我需要获取最新的这些文件,格式为 'order-export-(number).xml'。那些前缀为 'current-' 的应该被忽略。
我似乎无法让 Regex 正确执行此操作。这是我得到的:
<?php $src = '/public_html/folder/exports/';
$files_src = scandir($src, SCANDIR_SORT_DESCENDING);
foreach($files_src as $file) {
if (preg_match('/(^VS-), (.*)/A', $file) && !is_dir($src . $file)) {
$newest_file_src = $files_src[1];
$newest_file_path_src = $src . $files_src[1];
$dest_file_path = '/public_html/orders/';
rename($newest_file_path_src, $dest_file_path);
}
} ?>
有人可以指出我做错了什么吗?
提前致谢!
在您的模式中,您试图匹配逗号后跟不存在的 space。
对于更具体的模式,您可以使用
\AVS-order-export-\d+\.xml\z
\A
字符串开头VS-order-export-
字面匹配\d+\.xml
匹配1+个数字和.xml
\z
字符串结束
例如
if (preg_match('/\AVS-order-export-\d+\.xml\z/', $file)) {