簡體   English   中英

使用正則表達式對文件列表進行排序

[英]Using Regex to sort through a list of files

我正在編寫一個腳本來對文件列表進行排序,獲取與特定文件名匹配的最新文件,並將其復制到另一個文件夾。 我正在用 PHP 編寫它,然后使用 CRON 將其設置為每天在特定時間運行。

文件命名如下: VS-order-export-105.xml VS-order-export-104.xml current-VS-order-export-105,xml current-VS-order-export.104.xml

我需要獲取這些文件的最新版本,格式為“order-export-(number).xml”。 那些前綴為“current-”的應該被忽略。

我似乎無法讓正則表達式正確地做到這一點。 這是我所擁有的:

<?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);
    }
} ?>

請有人指出我做錯了什么嗎?

提前致謝!

在您的模式中,您試圖匹配一個逗號后跟一個不存在的空格。

對於更具體的模式,您可以使用

\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)) {

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM