正規表現を使用して数字を取得し、次を使用してゼロを埋めますsprintf()
。
$image_files = get_files($thumbpath);
foreach($image_files as $index=>$file) {
// Capture \d+ into $matches[1]
preg_match('/\((\d+)\)/', $file, $matches);
// Pad it with %04d in sprintf()
$newfile = sprintf("full-file%04d.jpg", $matches[1]);
}
例:
php > $file = 'full-file(12).jpg';
php > preg_match('/\((\d+)\)/', $file, $matches);
php > $newfile = sprintf("full-file%04d.jpg", $matches[1]);
php > echo $newfile;
// full-file0012.jpg
更新 (より柔軟なファイル名の場合):
反対票を投じた人を喜ばせるために、より柔軟なファイル名が必要だとしか思えないので、正規表現を展開します。
$image_files = get_files($thumbpath);
foreach($image_files as $index=>$file) {
preg_match('/([^(]+)\((\d+)\)(.+)/', $file, $matches);
$newfile = sprintf("%s%04d%s", $matches[1], $matches[2], $matches[3]);
// And rename the file
if (!rename($file, $newfile)) {
echo "Could not rename $file.\n";
}
else echo "Successfully renamed $file to $newfile\n";
}
パターンは最初に一致し、最初の までのすべてが に一致(
し([^(]+)
、その後に 経由で番号が続き、(\d+)
残りはすべて経由で一致し(.*)
ます。