先遍历目录文件,再用正则替换前缀。使用scandir()获取文件列表,跳过.和..,遍历中用preg_match匹配old_开头的文件名,捕获后缀并组合new_前缀生成新名,检查目标是否存在后执行rename重命名,避免覆盖;建议递归处理子目录、过滤扩展名、记录日志,并通过命令行传参提升复用性,操作前需备份或预览确认。

在PHP中批量替换文件名前缀,通常涉及遍历指定目录下的所有文件,使用正则表达式匹配原有前缀,并将其替换为新的前缀。这个过程适用于需要统一重命名大量文件的场景,比如项目重构、文件归档等。
使用PHP的scandir()或DirectoryIterator可以轻松读取目录中的文件。注意跳过.和..这两个特殊目录项。
示例代码:
$dir = '/path/to/your/directory';
$files = scandir($dir);
foreach ($files as $file) {
if ($file === '.' || $file === '..') {
continue;
}
$filePath = $dir . '/' . $file;
if (is_file($filePath)) {
// 处理文件重命名
}
}
假设你想将所有以old_开头的文件名改为new_开头,可以用preg_replace()进行匹配替换。
立即学习“PHP免费学习笔记(深入)”;
关键点:
$oldPrefix = 'old_';
$newPrefix = 'new_';
$pattern = '/^' . preg_quote($oldPrefix, '/') . '(.+)$/';
foreach ($files as $file) {
if ($file === '.' || $file === '..' || !is_file($dir . '/' . $file)) {
continue;
}
if (preg_match($pattern, $file, $matches)) {
$newFileName = $newPrefix . $matches[1];
$oldPath = $dir . '/' . $file;
$newPath = $dir . '/' . $newFileName;
if (!file_exists($newPath)) {
rename($oldPath, $newPath);
echo "已重命名: $file → $newFileName\n";
} else {
echo "跳过: $newFileName 已存在\n";
}
}
}
实际应用中可加入以下改进:
以上就是php如何批量替换文件名前缀_php遍历目录修改名称与正则匹配应用的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号