您可以使用preg_match
拉出數,那麼你可以使用copy
進行實際的系統副本:
function doCopy($file) {
preg_match('/TRK\s*#\s*(\d+)/', $file, $matches);
if (empty($matches[1])) { // no number, skip it
return false;
}
$folder = dirname($file) . DIRECTORY_SEPARATOR . $matches[1];
if (! is_dir($folder)) { // target directory doesn't exist: make it
mkdir($folder);
}
$target = $folder . DIRECTORY_SEPARATOR . basename($file);
echo "Copying '$file' into '$target'" . PHP_EOL;
return copy($file, $target); // actually copy now
}
然後,使用此功能循環播放您的文件,將會如下所示:
$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;
}
}
「魔術師」是在正則表達式/TRK\s*#\s*(\d+)/
,這說來匹配:
- 文本字符串「TRK」,
- 後跟任意數量的空格,然後是文字字符串
- 「#」,
- 後跟任意數量的空格,
- 後跟任意數字的位數 - 捕獲匹配的數字。
然後我們檢查是否有匹配的數字 - empty
測試 - 然後複製到一個以匹配值命名的目錄中。雜耍道路時我們必須小心。首先,目標目錄必須存在。其次,我們需要確保copy
可以在相應的目錄中找到原始文件,並且我們給它一個包含文件名的目標。超過一半的邏輯流向了這個開銷。
例一臺Linux機器上運行:
$ mkdir test
$ touch test/'TRK# 112 WeekDay# 5 From# BOB___Tender_P582895zdf112.pdf'
$ touch test/'TRK# WeekDay# 5 From# BOB___Tender_P588895zdf152.pdf'
$ touch test/'TRK# 115 WeekDay# 5 From# BOB___Tender_P582895zdf714.pdf'
$ cat example.php
<?php
function doCopy($file) {
preg_match('/TRK\s*#\s*(\d+)/', $file, $matches);
if (empty($matches[1])) {
return false;
}
$folder = dirname($file) . DIRECTORY_SEPARATOR . $matches[1];
if (! is_dir($folder)) {
mkdir($folder);
}
$target = $folder . DIRECTORY_SEPARATOR . basename($file);
echo "Copying '$file' into '$target'" . PHP_EOL;
return copy($file, $target);
}
$files = glob('test/*.pdf');
foreach ($files as $file) {
$copied = doCopy($file);
if (! $copied) {
echo "Did not copy $file" . PHP_EOL;
}
}
$ php example.php
Copying 'test/TRK# 112 WeekDay# 5 From# BOB___Tender_P582895zdf112.pdf' into 'test/112/TRK# 112 WeekDay# 5 From# BOB___Tender_P582895zdf112.pdf'
Copying 'test/TRK# 115 WeekDay# 5 From# BOB___Tender_P582895zdf714.pdf' into 'test/115/TRK# 115 WeekDay# 5 From# BOB___Tender_P582895zdf714.pdf'
Did not copy test/TRK# WeekDay# 5 From# BOB___Tender_P588895zdf152.pdf
$ tree test/
test/
├── 112
│ └── TRK#\ 112\ WeekDay#\ 5\ From#\ BOB___Tender_P582895zdf112.pdf
├── 115
│ └── TRK#\ 115\ WeekDay#\ 5\ From#\ BOB___Tender_P582895zdf714.pdf
├── TRK#\ 112\ WeekDay#\ 5\ From#\ BOB___Tender_P582895zdf112.pdf
├── TRK#\ 115\ WeekDay#\ 5\ From#\ BOB___Tender_P582895zdf714.pdf
└── TRK#\ WeekDay#\ 5\ From#\ BOB___Tender_P588895zdf152.pdf
這將是一個主要的正則表達式任務。你對正則表達式有什麼瞭解? – Goose
@Goose謝謝你的時間。主教也幫助我,但它看起來像我們遇到的問題。我認爲他有一個非常有前途的解決方案,但它還沒有工作。如果你可以查看它,那將非常棒!再次感謝。 – compcobalt