简体   繁体   中英

Using Regex to sort through a list of files

I'm writing a script to sort through a list of files, get the newest file which matches a particular file name, and copy it to another folder. I'm writing this in PHP, then setting it up to run at a certain time each day using a CRON.

The files are named likes this: VS-order-export-105.xml VS-order-export-104.xml current-VS-order-export-105,xml current-VS-order-export.104.xml

I need to get the latest of these files, with the pattern 'order-export-(number).xml'. Those prefixed 'current-' should be ignored.

I can't seem to get the Regex right to do this. Here's what I've got:

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

Please can someone point out what I'm doing wrong?

Thanks in advance!

In your pattern you are trying to match a comma followed by a space which are not present.

For a more specific pattern, you could use

\AVS-order-export-\d+\.xml\z
  • \\A Start of string
  • VS-order-export- Match literally
  • \\d+\\.xml Match 1+ digits and .xml
  • \\z End of string

Regex demo

For example

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM