compcobalt compcobalt - 1 month ago 7
PHP Question

PHP Copy/Send Files into Correct Folder

I have a lot of files that are named like this:


TRK# 112 WeekDay# 5 From# BOB___Tender_P582895zdf112
TRK# WeekDay# 5 From# BOB___Tender_P588895zdf152
TRK# 115 WeekDay# 5 From# BOB___Tender_P582895zdf714


I would like to send each file to its own folder.

Example:

TRK# 112 WeekDay# 5 From# BOB___Tender_P582895zdf112

would go inside folder 112

also,

TRK# WeekDay# 5 From# BOB___Tender_P588895zdf152
would not go anywhere because TRK# is empty/missing or it's not a number. IF ITS NOT A NUMBER SKIP IT.

and

TRK# 115 WeekDay# 5 From# BOB___Tender_P582895zdf714
would go into folder 115

Answer Source

You can use preg_match to pull out the number, then you can use copy to make the actual filesystem copy:

function doCopy($file) {
    preg_match('/TRK\s*#\s*(\d+)/', $file, $matches);
    if (! empty($matches[1])) {
        return copy($file, $matches[1] . DIRECTORY_SEPARATOR . $file);
    }
    return false;
}

Then a loop over your files, using this function, would go like:

$files = [
    'TRK# 112 WeekDay# 5 From# BOB___Tender_P582895zdf112',
    'TRK# WeekDay# 5 From# BOB___Tender_P588895zdf152',
    'TRK# 115 WeekDay# 5 From# BOB___Tender_P582895zdf714',
];

foreach ($files as $file) {
    $copied = doCopy($file);
    if (! $copied) {
        echo "Did not copy $file" . PHP_EOL;
    }
}

The "magic" is in the regular expression /TRK\s*#\s*(\d+)/, which says to match:

  1. the literal string "TRK",
  2. followed by any number of spaces,
  3. followed by the literal string "#",
  4. followed by any number of spaces,
  5. followed by any number of digits -- while capturing the matched digits.

We then check if there are matched digits -- the ! empty test -- and do a copy into a directory named with that matched value.