【问题标题】:Using Regex to sort through a list of files使用 Regex 对文件列表进行排序
【发布时间】:2020-03-25 10:48:30
【问题描述】:

我正在编写一个脚本来对文件列表进行排序,获取与特定文件名匹配的最新文件,并将其复制到另一个文件夹。 我正在用 PHP 编写它,然后使用 CRON 将其设置为每天在特定时间运行。

文件命名如下: VS-order-export-105.xml VS-order-export-104.xml 当前-VS-order-export-105,xml 当前-VS-order-export.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);
    }
} ?>

请有人指出我做错了什么?

提前致谢!

【问题讨论】:

  • 您只是想获取最新的“VS-order-export-###”文件,还是需要其他一些“VS-something-something”文件来做同样的事情?
  • 最新的VS-order-export-###文件
  • 您要匹配的文件名中没有逗号和空格。如需更具体的匹配,请尝试^VS-order-export-\d+\.xml$ regex101.com/r/atBs9C/1
  • 谢谢@第四只鸟。这几乎可以工作,除了我在“gm”选项中遇到如下错误: PHP 警告:preg_match(): Unknown modifier 'g' 关于如何解决这个问题有什么想法吗?
  • 啊!现在可以了。感谢您的帮助@第四只鸟

标签: php regex preg-match


【解决方案1】:

在您的模式中,您尝试匹配逗号后跟不存在的空格。

对于更具体的模式,您可以使用

\AVS-order-export-\d+\.xml\z
  • \A 字符串开始
  • VS-order-export- 字面匹配
  • \d+\.xml 匹配 1+ 个数字和 .xml
  • \z 字符串结束

Regex demo

例如

if (preg_match('/\AVS-order-export-\d+\.xml\z/', $file)) {

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-25
    • 2018-07-03
    • 2013-04-23
    • 2010-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-21
    相关资源
    最近更新 更多