【问题标题】:Find duplicate files by names with PHP使用 PHP 按名称查找重复文件
【发布时间】:2016-08-26 16:04:35
【问题描述】:

项目中有一些模块正在被重命名或新建或直接复制。现在我想删除旧的目录文件。所以我想找到所有具有相同名称的文件及其路径以进行清理。 (计数 > 2)。可以是 css、tpl、php 或 js 文件。

Main\Games\troy.php
Main\Games\Child Games\troy.php
Main\Games\Sports\troy.php

如果在主目录上进行搜索,则搜索应返回所有 3 个文件及其路径。如何通过 PHP 查找重复文件。

这对于在您的驱动器中查找具有相同名称的重复文件(如 mp3、3gp 文件)也很有用。

【问题讨论】:

标签: php performance duplicates filesystems


【解决方案1】:
function find_duplicate_files() {
    $names = scandir_recursive( 'D:\Main' );
    $files = array();
    foreach( $names as $name ) {
        if( count( $name ) > 1 ) {
            $files[] = $name;
        }
    }
    print_r( $files );
}

函数scandir_recursive()递归解析指定的目录树并创建一个关联数组,其键是在所有子目录中找到的文件名,其值是对应的路径。

function scandir_recursive( $dir, &$result = array() ) {
    $dir = rtrim($dir, DIRECTORY_SEPARATOR);

    foreach ( scandir($dir) as $node ) {
        if ($node !== '.' and $node !== '..') {
            if (is_dir($dir . DIRECTORY_SEPARATOR . $node)) {
                scandir_recursive($dir . DIRECTORY_SEPARATOR . $node, $result);
            } else {
                $result[$node][] = $dir . DIRECTORY_SEPARATOR . $node;
            }
        }
    }
    return $result;
}

// 会像这样输出

Array
(
    [0] => Array
        (
            [0] => D:\Main\Games\troy.php
            [1] => D:\Main\Games\Child Games\troy.php
            [2] => D:\Main\Games\Sports\troy.php 
        )

    [1] => Array
        (
            [0] => D:\Main\index.php
            [1] => D:\Main\Games\index.php
        )
)

从中我们可以识别哪些是重复文件。当您的代码库有大量文件时,它很有用。 (而且我经常用它来查找重复的音乐 mp3 文件:P)

【讨论】:

  • 我建议你看一下 PHP 的递归目录迭代器,而不是 scandir_recursive:php.net/class.recursivedirectoryiterator - 然后你可以更专注于计数逻辑,而不是递归遍历。
  • @hakre:你能举个例子吗?我不明白你的意思。有没有办法通过内置函数找到。
  • 示例在 PHP 手册链接和底部的这个答案中给出:stackoverflow.com/a/12236744/367456
猜你喜欢
  • 2018-05-04
  • 1970-01-01
  • 1970-01-01
  • 2017-01-23
  • 2020-08-12
  • 1970-01-01
  • 2013-11-07
  • 1970-01-01
  • 2014-06-02
相关资源
最近更新 更多